Java Reference
In-Depth Information
which contains either
true
or
false
. If it contains
true
, the underlying
XMLHttpRequest
object
uses asynchronous communication to retrieve the file. If
false
, the module uses synchronous
communication.
The first change made to the module is in the constructor itself. The original constructor initializes
and readies the
XMLHttpRequest
object to send data. This will not do for this new version, however.
Instead, the constructor merely initializes all the properties:
function HttpRequest(url, callback) {
this.url = url;
this.callBack = callback;
this.async = true;
this.request = new XMLHttpRequest();
};
You have three new properties here. The first,
url
, contains the URL that the
XMLHttpRequest
object should attempt to request from the server. The
callBack
property contains a reference
to the callback function, and the
async
property determines the type of communication the
XMLHttpRequest
object uses. Setting
async
to
true
in the constructor gives the property a default
value. Therefore, you can send the request in asynchronous mode without setting the property
externally.
The new constructor and properties are actually desirable, because they enable you to reuse the
same
HttpRequest
object for multiple requests. If you wanted to make a request to a different
URL, all you would need to do is assign the
url
property a new value. The same can be said for the
callback function as well.
The majority of changes to the module are in the
send()
method. It is here that the module decides
whether to use asynchronous or synchronous communication. Both types of communication have
very little in common when it comes to making a request; asynchronous communication uses
the
onreadystatechange
event handler, and synchronous communication allows access to the
XMLHttpRequest
object's properties when the request is complete. Therefore, code branching is required:
HttpRequest.prototype.send = function() {
this.request.open("GET", this.url, this.async);
if (this.async) {
//more code here
}
this.request.send(null);
if (!this.async) {
//more code here
}
}
The first line of this method uses the
open()
method of the
XMLHttpRequest
object. The
async
property is used as the final parameter of the method. This determines whether or not the XHR
object uses asynchronous communication. Next, an
if
statement tests to see if
this.async
is
true
; if it is, the asynchronous code will be placed in this
if
block. Next, the
XMLHttpRequest
object's
send()
method is called, sending the request to the server. The final
if
statement checks