AJAX - The Complete Reference

(avery) #1

Chapter 3: XMLHttpRequest Object 77


PART I


to note the implications of the synchronous communication. The browser, in effect, blocks
on the line xhr.send(null) until the communication returns. Given the possibility
for network delays and problems, this probably isn’t the way to go except for important
transactions. You can demonstrate this for yourself by running the example at
http://ajaxref.com/ch3/syncsendslow.html. This example will block on the server for
5 seconds, giving plenty of time to note that your browser won’t let you do anything else.
While the asynchronous requests discussed in the next section do not exhibit such
problems, they do introduce extra complexity to address.

Asynchronous Requests


To make the previous example perform its request asynchronously, the first change is to set
the asynchronous parameter to true in the open() method.

xhr.open("GET", "http://ajaxref.com/ch3/helloworld.php", true);

However, where to put the code to handle the returned data is not immediately obvious.
To address the response, a callback function must be defined that will be awoken as the
response is received. To do this, associate a function with the XHR’s onreadystate property.
For example, given a function called handleResponse, set the onreadystatechange
property like so:

xhr.onreadystatechange = handleResponse;

Unfortunately, when set like this, it is not possible to pass any parameters to the callback
function directly and thus it tends to lead to the use of global variables. Instead, use an
inner function called a closure to wrap the function call and any values it might use, like so:

xhr.onreadystatechange = function(){handleResponse(xhr);};

Now the handleResponse function is going to get called a number of times as the request
is processed. As the function is called, it is possible to observe the progress of the request by
looking at the XHR’s readyState property. However, at this point in the discussion the focus
is simply on knowing when the request is done as indicated by a readyState value of 4. Also,
it is important that the HTTP request must be successful as indicated by a status property
value of 200 corresponding to the HTTP response line “200 OK”. The handleResponse
function shown next shows all these ideas in action.

function handleResponse(xhr)
{
if (xhr.readyState == 4 && xhr.status == 200)
{
var responseOutput = document.getElementById("responseOutput");
responseOutput.innerHTML = "<h3>reponseText</h3>" + xhr.responseText;
responseOutput.style.display = "";
}
}
Free download pdf