jQuery in Action
Brushing up on Ajax
219
8.1.1 Creating an XHR instance
In a perfect world, code written for one browser would work in all commonly used
browsers. We've already learned that we don't live in that world; things don't
change with Ajax. There is a standard means to make asynchronous requests via
the JavaScript
browsers. We've already learned that we don't live in that world; things don't
change with Ajax. There is a standard means to make asynchronous requests via
the JavaScript
XHR
object, and an Internet Explorer proprietary means that uses
an ActiveX control. With
IE7
, a wrapper that emulates the standard interface is
available, but
IE6
requires divergent code.
Once created (thankfully) the code to set up, initiate, and respond to the
request is relatively browser-independent, and creating an instance of
XHR
is easy
for any particular browser. The problem is that different browsers implement
XHR
in different ways, and we need to create the instance in the manner appro-
priate for the current browser.
But rather than relying on detecting which browser a user is running to deter-
mine which path to take, we'll use the preferred technique known as object detec-
tion. In this technique, we try to figure out what the browser's capabilities are, not
which browser is being used. Object detection results in more robust code because
it can work in any browser that supports the tested capability.
tion. In this technique, we try to figure out what the browser's capabilities are, not
which browser is being used. Object detection results in more robust code because
it can work in any browser that supports the tested capability.
The code of listing 8.1 shows a typical idiom used to instantiate an instance of
XHR
using this technique.
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
After creation, the
XHR
instance sports a conveniently consistent set of properties
and methods across all supporting browser instances. These properties and
methods are shown in table 8.1, and the most commonly used of these will be dis-
cussed in the sections that follow.
methods are shown in table 8.1, and the most commonly used of these will be dis-
cussed in the sections that follow.
With an instance created, let's look at what it takes to set up and fire off the
request to the server.
Listing 8.1
Object detection resulting in code that can deal with many browsers
Tests to see if
XHR is defined
XHR is defined
Tests to see if
ActiveX is present
ActiveX is present
Throws error if there's no XHR support