402
Appendix II
ajax.js
You’ve seen this code plenty of times by now. This little bit of JavaScript takes care of
creating a request object, and makes sure that the object will work on all modern web
browsers, from Internet Explorer to Firefox to Opera. Get used to this code if you’re not
already... it’s the foundation of every Ajax application.
var request = null;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject(“Msxml2.XMLHTTP”);
} catch (othermicrosoft) {
try {
request = new ActiveXObject(“Microsoft.XMLHTTP”);
} catch (failed) {
request = null;
}
}
}
if (request == null)
alert(“Error creating request object!”);
You’ll see a lot of code that uses false
here, instead of null, but that won’t work
on some versions of IE. Stick with null, and
your code will work on all platforms.
We put all this code in a le called ajax.js.
You can call it anything you like, as long as
you change your HTML <script> tag to refer
to the right lename.
Remember, you’ve got to
try XMLHttpRequest
for browsers like Opera
and Mozilla, and then
try ActiveXObject for
Internet Explorer.
OK, we admit it... this isn’t the most
robust way to handle errors. By now,
though, you’re ready to add some more
advanced error handling on your own.
Follow the code... things end up here
if all the different attempts at
creating a request object fail.
creating a request object