Java Reference
In-Depth Information
}
}
this.request.onreadystatechange = reqReadyStateChange;
}
The new lines of code may once again look a little strange, but it's actually a pattern you'll often
see when looking at other people's code. The first new line creates the
tempRequest
variable.
This variable is a pointer to the current object's
request
property, and it's used within the
reqReadyStateChange()
function. This is a technique to get around scoping issues. Ideally, you
would use
this.request
inside the
reqReadyStateChange()
function. However, the
this
keyword
points to the
reqReadyStateChange()
function instead of to the
XMLHttpRequest
object, which
would cause the code to not function properly. So when you see
tempRequest
, think
this.request
.
Inside the
reqReadyStateChange()
function, you see the following line:
callback(tempRequest.responseText);
This line calls the callback function specified by the constructor's
callback
parameter, and you
pass the
responseText
property to this function. This allows the callback function to use the
information received from the server.
Creating the send() method
There is one method in this reference type, and it enables you to send the request to the server.
Sending a request to the server involves the
XMLHttpRequest
object's
send()
method. This
send()
is
similar, with the difference being that it doesn't accept arguments:
HttpRequest.prototype.send = function () {
this.request.send(null);
};
This version of
send()
is simple in that all you do is call the
XMLHttpRequest
object's
send()
method and pass it
null
.
the full Code
Now that the code's been covered, open your text editor and type the following:
function HttpRequest(url, callback) {
this.request = new XMLHttpRequest();
this.request.open("GET", url);
var tempRequest = this.request;
function reqReadyStateChange() {
if (tempRequest.readyState == 4) {
if (tempRequest.status == 200) {
callback(tempRequest.responseText);
} else {
alert("An error occurred trying to contact the server.");
}