Java Reference
In-Depth Information
With the properties and methods identifi ed, let's begin to write the module.
The HttpRequest Constructor
A reference type's constructor defi nes its properties and performs any logic needed to function properly.
function HttpRequest(sUrl, fpCallback)
{
this.request = this.createXmlHttpRequest();
//more code here
}
The constructor accepts two arguments. The fi rst, sUrl, is the URL the XMLHttpRequest object will
request. The second, fpCallback, 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 fi rst line of the constructor
initializes the request property, assigning an XMLHttpRequest object to it.
With the request property created and ready to use, it's time to prepare the request for sending.
function HttpRequest(sUrl, fpCallback)
{
this.request = this.createXmlHttpRequest();
this.request.open(“GET”, sUrl, true);
function request_readystatechange()
{
//more code here
}
this.request.onreadystatechange = request_readystatechange;
}
The fi rst line of the new code uses the XMLHttpRequest object's open() method to initialize the
request object. Set the request type to GET, use the sUrl parameter to specify the URL you want
to request, and set the request object to use asynchronous mode. The next few lines defi ne the request_
readystatechange() function. Defi ning a function within a function may seem weird, but it is perfectly
legal to do so; it's an advanced technique called a closure . Closures, like the request_readystatechange()
function, cannot be accessed outside their containing function (the constructor in this case), but they have
access to the variables and parameters of the containing function. This 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(sUrl, fpCallback)
{
this.request = this.createXmlHttpRequest();
this.request.open(“GET”, sUrl, true);
var tempRequest = this.request;
function request_readystatechange()
{
Search WWH ::




Custom Search