Java Reference
In-Depth Information
the httprequest Constructor
A reference type's constructor defines its properties and performs any logic needed to function
properly:
function HttpRequest(url, callback) {
this.request = new XMLHttpRequest();
//more code here
}
The constructor accepts two arguments. The first,
url
, is the URL the
XMLHttpRequest
object will
request. The second,
callback
, is a callback function; it will be called when the server's response is
received (when the request's
readyState
is
4
and its
status
is
200
). The first line of the constructor
initializes the
request
property, assigning an
XMLHttpRequest
object to it.
With the
request
property created and ready to use, you prepare to send the request:
function HttpRequest(url, callback) {
this.request = new XMLHttpRequest();
this.request.open("GET", url);
function reqReadyStateChange() {
//more code here
}
this.request.onreadystatechange = reqReadyStateChange;
}
The first line of the new code uses the
XMLHttpRequest
object's
open()
method to initialize the request
object. Set the request type to
GET
, and use the
url
parameter to specify the URL you want to request.
Because you omit
open()
's third argument, you set the request object to use asynchronous mode.
The next few lines define the
reqReadyStateChange()
function. Defining a function within
a function may seem weird, but it is perfectly legal to do so. This inner function cannot be
accessed outside the containing function (the constructor in this case), but it has access to
the variables and parameters of the containing constructor function. As its name implies, the
reqReadyStateChange()
function handles the request object's
readystatechange
event, and you
bind it to do so by assigning it to the
onreadystatechange
event handler:
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.");
}