AJAX - The Complete Reference

(avery) #1

74 Part I: Core Ideas


function createXHR()
{
try { return new XMLHttpRequest(); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
return null;
}

To create a cross-browser XHR object, all you need to do is call the wrapper function
and make sure it returns something.

var xhr = createXHR();
if (xhr)
{
// Engage the XHR!
}

Now with XHR in hand it is time to use it to make a request.

NNOT EOTE There is a Java-based browser called IceBrowser that supports an alternate form of XHR
creation, window.createRequest(), which you could have added to your wrapper. Other
esoteric browsers may also use alternative XHR syntax, but we avoid promoting such esoteric
oddities except to make you aware of their possible existence.

XHR Request Basics


Once the XHR object is created, most of the cross-browser concerns subside—for the
moment, at least. To invoke an XHR request, all browsers use the same syntax:

xhr.open(method, url, async [ ,username, password ])

where method is an HTTP method like GET, POST, HEAD. While these values are not case-
sensitive, they should be in uppercase as per the HTTP specification. The parameter url is the
particular URL to call and maybe either relative or absolute. The async parameter is set to
true if the request is to be made asynchronously or false if it should be made synchronously.
If not specified, the request will be made asynchronously. The optional parameters username
and password are used when attempting to access a resource that is protected with HTTP
Basic authentication. We will explore that later in the chapter, but these parameters won’t be
very useful given the way browsers implement this feature.

Synchronous Requests


We start the discussion of XHR-based communication with the simplest example: performing
a synchronous request. First, the wrapper function is used to create an XHR. Next, a connection
is opened using the syntax presented in the previous section. In this case, the URL is set to a very
basic PHP program that will echo back the IP address of the user accessing it and the local server
time. Finally, the request is sent on its way by invoking the XHR’s send() method. It should be
Free download pdf