Java Reference
In-Depth Information
to see whether
this.async
is
false
. If it is, synchronous code is placed within the code block to
execute.
HttpRequest.prototype.send = function() {
this.request.open("GET", this.url, this.async);
if (this.async) {
var tempRequest = this.request;
var callback = this.callBack;
function requestReadystatechange() {
if (tempRequest.readyState == 4) {
if (tempRequest.status == 200) {
callback(tempRequest.responseText);
} else {
alert("An error occurred while attempting to " +
"contact the server.");
}
}
}
this.request.onreadystatechange = requestReadystatechange;
}
this.request.send(null);
if (!this.async) {
this.callBack(this.request.responseText);
}
};
This new code finishes off the method. Starting with the first
if
block, a new variable called
callback
is assigned the value of
this.callBack
. This is done for the same reasons as with the
tempRequest
variable—scoping issues—because
this
points to the
requestReadystatechange()
function instead of the
HttpRequest
object. Other than this change, the asynchronous code remains
the same. The
requestReadystatechange()
function handles the
readystatechange
event and
calls the callback function when the request is successful.
The second
if
block is much simpler. Because this code executes only if synchronous
communication 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 fictitious text file called
test.txt
:
function requestCallback(responseText) {
alert(responseText);
}
var http = new HttpRequest("test.txt", requestCallback);
http.send();