Java Reference
In-Depth Information
oHttp.send(null);
if (oHttp.status == 200)
{
alert(“The text file was found!”);
}
else
{
alert(“The server returned a status code of ” + oHttp.status);
}
This code performs the same basic function, but it only checks for a status code of 200 and alert a
generic message to the user for other status codes.
Asynchronous Requests
The previous code samples demonstrate the simplicity of synchronous requests. Asynchronous requests,
on the other hand, add some complexity to your code because you have to handle the readystatechange
event. In asynchronous requests, the XMLHttpRequest object exposes a readyState property, which
holds a numeric value; each value refers to a specifi c state in a request's lifespan, as follows:
— The object has been created, but the open() method hasn't been called
0
1
— The open() method has been called, but the request hasn't been sent
— The request has been sent; headers and status are received and available
2
3
— A response has been received from the server
— The requested data has been fully received
4
The readystatechange event fi res every time the readyState property changes, calling the
onreadystatechange event handler. The fourth and fi nal state is the most important; it lets you
know that the request completed.
It is important to note that even if the request was successful, you may not have the information you
wanted. An error may have occurred on the server's end of the request (a 404 , 500 , or some other
error). Therefore, you still need to check the status code of the request.
Code to handle the readystatechange event could look like this:
var oHttp = createXmlHttpRequest();
function oHttp_readyStateChange()
{
if (oHttp.readyState == 4)
{
if (oHttp.status == 200)
{
alert(oHttp.responseText);
}
else
{
Search WWH ::




Custom Search