readyState == 4)
{
// Continue only if HTTP status is "OK"
if (xmlHttp.status == 200)
{
// Retrieve the response
response = xmlHttp.responseText;
// Do something with the response
// ...
}
}
}
Before attempting to read the received data, we also verify that the response status code
is 200. Sending such a code indicates the status of the request is part of the HTTP protocol,
and 200 is the status code that specifies that the request completed successfully. Other popular
HTTP status codes are 404, which indicates that the requested resource couldn??™t be found,
and 500, which indicates a server error.
Once again we can use try-catch blocks to handle errors that could happen while initiating
a connection to the server or while reading the response from the server. An improved
version of the handleRequestStateChange() function looks like this:
// Function executed when the state of the request changes
function handleRequestStateChange()
{
// Continue if the process is completed
if (xmlHttp.readyState == 4)
{
// Continue only if HTTP status is "OK"
if (xmlHttp.status == 200)
{
try
{
// Retrieve the response
response = xmlHttp.responseText;
// Do something with the response
// ...
}
catch(e)
{
// Display error message
alert("Error reading the response: " + e.toString());
CHAPTER 13 ?– IMPLEMENTING AJAX FEATURES 408
}
}
else
{
// Display status message
alert("There was a problem retrieving the data:\n" + xmlHttp.
Pages:
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524