AJAX - The Complete Reference

(avery) #1

3 XMLHttpRequest Object


T


he techniques discussed in the previous chapter use common JavaScript and XHTML
features, often in ways and for purposes other than those for which they were intended.
As such, these communication approaches generally lack necessary features for building
a robust Ajax-style application. Specifically, to build a proper Ajax-style application you will
need fine control over communication, including the ability to get and set HTTP headers, read
response codes, and deal with different kinds of server-produced content. JavaScript’s
XMLHttpRequest (XHR) object can be used to address nearly all of these problems and thus
is at the heart of most Ajax applications. However, there are limitations to XHRs that should
be acknowledged, so in this chapter, the aim is to present not only a complete overview of
the object’s syntax and its use, but an honest discussion of its limitations as well.

Overview of XHRs


At the heart of Ajax is the XHR object. A bit misnamed, this object provides generalized
HTTP or HTTPS access for client-side scripting and is not limited to just making requests or
using XML, as its name would suggest. The facility was first implemented in Internet
Explorer 5 for Windows to support the development of Microsoft Outlook Web Access for
Exchange 2000, and this object has come to be widely supported in all major desktop
browsers. Native implementations can be found in Safari 1.2+, Mozilla 1+, Netscape 7+,
Opera 8+, and Internet Explorer 7+. ActiveX-based implementations are found in Internet
Explorer 5, 5.5, and 6. Browser support for XHRs is summarized in Table 3-1.
Given the ubiquity of the object, the W3C aims to standardize its syntax (http://w3.org/
TR/XMLHttpRequest/), though browser variations do exist, as you will see in a moment.
Table 3-2 summarizes the common properties and methods for the XHR object.

NNOT EOTE While XML prefixes the name of this object, its only major tie-in with XML is that responses
may be parsed as XML via the responseXML property. XML data interchange certainly is not
required by XHRs as will be demonstrated in numerous examples.

Like anything in a Web browser, specific features can be found in XHR objects, as shown
in Table 3-3. Why so much “innovation” occurs in Web browser technology is a matter of
debate, with some citing conspiracy and others simple acknowledging that we Web
developers are never satisfied with the status quo.

61


CHAPTER


http://www.ebooks.org.in

Free download pdf