Java Reference
In-Depth Information
fpCallback(tempRequest.responseText);
}
else
{
alert(“An error occurred while attempting to “ +
“contact the server.”);
}
}
}
this.request.onreadystatechange = request_readystatechange;
}
this.request.send(null);
if (!this.async)
{
this.callBack(this.request.responseText);
}
}
This new code fi nishes off the method. Starting with the fi rst
if
block, a new variable called
fpCallback
is assigned the value of
this.callBack
. This is done for the same reasons as with the
tempRequest
variable — scoping issues — as
this
points to the
request_readystatechange()
function instead
of the
HttpRequest
object. Other than this change, the asynchronous code remains the same. The
request_readystatechange()
function handles the
readystatechange
event and calls the call-
back function when the request is successful.
The second
if
block is much simpler. Because this code executes only if synchronous communica-
tion is desired, all you have to do is call the callback function and pass the
XMLHttpRequest
object's
responseText
property.
Using this newly refactored module is quite simple. The following code makes an asynchronous
request for a fi ctitious text fi le called
test.txt
.
function request_callback(sResponseText)
{
alert(sResponseText);
}
var oHttp = new HttpRequest(“test.txt”, request_callback);
oHttp.send();
Nothing has really changed for asynchronous requests. This is the exact same code used earlier in the
chapter. If you want to use synchronous communication, simply set
async
to
false
, like this:
function request_callback(sResponseText)
{
alert(sResponseText);
}
var oHttp = new HttpRequest(“test.txt”, request_callback);