Java Reference
In-Depth Information
if (tempRequest.status == 200)
{
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);
}
}
It's possible to add synchronous communication to your
HttpRequest
module in a variety of ways.
The approach in this solution refactors the code to accommodate a new property called
async
, which
contains either
true
or
false
. If it contains
true
, then the underlying
XMLHttpRequest
object uses
asynchronous communication to retrieve the fi le. If
false
, the module uses synchronous communica-
tion. In short, this property resembles an XML DOM's
async
property for determining how an XML
document is loaded.
The fi rst 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(sUrl, fpCallback)
{
this.url = sUrl;
this.callBack = fpCallback;
this.async = true;
this.request = this.createXmlHttpRequest();
}
There are three new properties here. The fi rst,
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, as they enable you to reuse the same
HttpRequest
object for multiple requests. If you wanted to make a request to a different URL, all