Java Reference
In-Depth Information
} else {
alert("The server returned a status code of " + status);
}
}
}
 
request.open("GET", " http://localhost/myTextFile.txt");
request.onreadystatechange = reqReadyStateChange;
 
request.send(null);
This code first defines the reqReadyStateChange() function, which handles the readystatechange
event. It first checks if the request completed by comparing readyState to 4 . The function then
checks the request's status to ensure the server returned the requested data. Once these two criteria
are met, the code alerts the value of the responseText property (the actual requested data in
plaintext format). Note the open() method's call; the third argument is omitted. This makes the
XMLHttpRequest object request data asynchronously.
The benefits of using asynchronous communication are well worth the added complexity of the
readystatechange event, because the browser can continue to load the page and execute your other
JavaScript code while the request object sends and receives data. Perhaps a user‐defined module that
wraps an XMLHttpRequest object could make asynchronous requests easier to use and manage.
Note   An XMLHttpRequest object also has a property called responseXML ,
which attempts to load the received data into an HTML DOM (whereas
responseText returns plaintext).
Creating a simple ajax module
The concept of code reuse is important in programming; it is the reason why functions are defined
to perform specific, common, and repetitive tasks. Chapter 5 introduced you to the object‐oriented
construct of code reuse: reference types. These constructs contain properties that contain data and/
or methods that perform actions with that data.
In this section, you write your own Ajax module called HttpRequest , thereby making asynchronous
requests easier to make and manage. Before getting into writing this module, let's go over the
properties and methods the HttpRequest reference type exposes.
planning the httprequest module
There's only one piece of information that you need to keep track of: the underlying
XMLHttpRequest object. Therefore, this module will have only one property, request , which
contains the underlying XMLHttpRequest object.
The HttpRequest exposes a single method called send() . Its purpose is to send the request to the
server.
Now let's begin to write the module.
 
Search WWH ::




Custom Search