Datasheet
In Mozilla Firefox, IE 7, and other browsers, it is created as follows:
var xHRObject = new XMLHttpRequest();
In turn, this means that you have to do a little bit of browser feature detection before you can determine
in which way the object needs to be created. Because ActiveX controls and objects are unique to IE, you
can test for them by attempting to call the
ActiveXObject method of the window object. For IE 7,
Mozilla Firefox, Safari, and Opera, there is an
XMLHttpRequest method. These calls use implicit type
conversion to return
true or false, depending on which browser is being used to view the page. In
other words, if there is an
ActiveXObject on that browser, it will return true. If not, it will return
false.
Typically your browser feature detection and object creation code would look something like this:
var xHRObject = false;
if (window.XMLHttpRequest)
{
xHRObject = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xHRObject = new ActiveXObject(“Microsoft.XMLHTTP”);
}
else
{
//Do something to handle non-Ajax supporting browsers.
}
There are plans to standardize this functionality in level 3 of the DOM specification, but until then, you
will need to make allowances for this fact.
The role the
XMLHttpRequest object plays is a major one. It is used heavily in Google’s Gmail to ferry
the data backward and forward behind the scenes. In fact, it can provide the asynchronous part of the
Ajax application. It uses the
onreadystatechange event to indicate when it has finished loading infor-
mation. You can tell it to get an XML document as shown here:
xHRObject.open(“GET”, “SuiteList.xml”, true);
Then, at a later point, you can check the value of the readyState property to see if it has finished load-
ing and, if it has, then extract the information that you need.
The
XMLHttpRequest object is misleading in one sense, in that you don’t have to transfer XML with it.
You can quite happily use it to transfer HTML or just plain text back and forth as well. The
XMLHttp
Request
is examined in more detail in Chapter 4. The difference between synchronous and asyn-
chronous methods of data transfer is examined later in this chapter.
Server-Side Technologies
The last piece of this equation (and one not really touched on in Garrett’s original article) is the server-
side technologies that Ajax will need to use. This book uses PHP and ASP.NET (where appropriate) to
service requests to the server. Any one method is not better than another; rather, you should use the one
that you are most familiar with.
15
Chapter 1: Introducing Ajax
04_106754 ch01.qxp 2/9/07 6:15 PM Page 15