open("GET", "server_script.php", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
This implementation has the following potential problems:
??? process() may be executed even if xmlHttp doesn??™t contain a valid XMLHttpRequest instance.
This may happen if, for example, the user??™s browser doesn??™t support XMLHttpRequest. This
would cause an unhandled exception to happen. Our other efforts to handle errors don??™t
help very much if we aren??™t consistent and do something about the process function as well.
??? process() isn??™t protected against other kinds of errors that could happen. For example,
as you will see later in this chapter, some browsers will generate a security exception if
they don??™t like the server you want to access with the XMLHttpRequest object.
CHAPTER 13 ?– IMPLEMENTING AJAX FEATURES 406
A better version of process() looks like this:
// Performs a server request and assigns a callback function
function process()
{
// Continue only if xmlHttp isn't void
if (xmlHttp)
{
// Try to connect to the server
try
{
// Initiate server request
xmlHttp.open("GET", "server_script.php", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
// Display an error in case of failure
catch (e)
{
alert("Can't connect to server:\n" + e.toString());
}
}
}
If xmlHttp is null (or false), we don??™t display yet another error message, because we
assume such amessage was already displayed by the createXmlHttpRequestObject function.
Pages:
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522