1、Using the XMLHttpRequest Object Now that weve discussed the history of dynamic Web applications and introduced Ajax, its time to cover the heart of the matter: how to use the XMLHttpRequest object. While Ajax is more of a technique than a technology, without widespread support for XMLHttpRequest, Go
2、ogle Suggest and Ta-da List wouldnt exist as we currently know them. And you wouldnt be reading this book! XMLHttpRequest was originally implemented in Internet Explorer 5 as an ActiveX component. That it worked only in Internet Explorer kept most developers from using XMLHttpRequest until its recen
3、t adoption as a de facto standard in Mozilla 1.0 and Safari 1.2. Its important to note that XMLHttpRequest is not a W3C standard, though much of the functionality is covered in a new proposal: the DOM Level 3 Load and Save Specification. Because it is not a standard, its behavior may differ slightly
4、 from browser to browser, though most methods and properties are widely supported. Currently, Firefox, Safari, Opera, Konqueror, and Internet Explorer all implement the behavior of the XMLHttpRequest object similarly. That said, if a significant number of your users still access your site or applica
5、tion with older browsers, you will need to consider your options. As we discussed in Chapter 1, if you are going to use Ajax techniques, you need to either develop an alternative site or allow your application to degrade gracefully. With most usage statistics indicating that only a small fraction of
6、 browsers in use today lack XMLHttpRequest support, the chances of this being a problem are slim. However, you need to check your Web logs and determine what clients your customers are using to access your sites. Overview of the XMLHttpRequest Object You must first create an XMLHttpRequest object us
7、ing JavaScript before you can use the object to send requests and process responses. Since XMLHttpRequest is not a W3C standard, you can use JavaScript in a couple of ways to create an instance of XMLHttpRequest. Internet Explorer implements XMLHttpRequest as an ActiveX object, and other browsers su
8、ch as Firefox, Safari, and Opera implement it as a native JavaScript object. Because of these differences, the JavaScript code must contain logic to create an instance of XMLHttpRequest using the ActiveX technique or using the native JavaScript object technique. The previous statement might send shi
9、vers down the spines of those who remember the days when the implementation of JavaScript and the DOM varied widely among browsers. Fortunately, in this case you dont need elaborate code to identify the browser type to know how to create an instance of the XMLHttpRequest object. All you need to do i
10、s check the browsers support of ActiveX objects. If the browser supports ActiveX objects, then you create the XMLHttpRequest object using ActiveX. Otherwise, you create it using the native JavaScript object technique. If the call to window.ActiveXObjectfails, then the JavaScript branches to the else
11、statement, which determines whether the browser implements XMLHttpRequest as a native JavaScript object. If window.XMLHttpRequestexists, then an instance of XMLHttpRequest is created. Thanks to JavaScripts dynamically typed nature and that XMLHttpRequest implementations are compatible across various
12、 browsers, you can access the properties and methods of an instance of XMLHttpRequest identically, regardless of the method used to create the instance. This greatly simplifies the development process and keeps the JavaScript free of browser-specific logic. Methods and Properties Table 2-1 shows som
13、e typical methods on the XMLHttpRequest object. Dont worry; well talk about these methods in greater detail in a moment. Table 2-1. Standard XMLHttpRequest Operations Method Description abort() The current request. getAllResponseHeaders() Returns all the response headers for the HTTP request as key/
14、value pairs. getResponseHeader(header) Returns the string value of the specified header. open(method, url) Sets the stage for a call to the server. The method argument can be either GET, POST, or PUT. The url argument can be relative or absolute. This method includes three optional arguments. send(c
15、ontent) Sends the request to the server. setRequestHeader(header, value) Sets the specified header to the supplied value. open() must be called before attempting to set any headers. Lets take a closer look at these methods. void open(string method, string url, boolean asynch, string username, string
16、 password): This method sets up your call to the server. This method is meant to be the script-only method of initializing a request. It has two required arguments and three optional arguments. You are required to supply the specific method you are invoking (GET, POST, or PUT) and the URL of the res
17、ource you are calling. You may optionally pass a Boolean indicating whether this call is meant to be asynchronous the default is true, which means the request is asynchronous in nature. If you pass a false, processing waits until the response returns from the server. Since making calls asynchronousl
18、y is one of the main benefits of using Ajax, setting this parameter to false somewhat defeats the purpose of using the XMLHttpRequest object. That said, you may find it useful in certain circumstances such as validating user input before allowing the page to be persisted. The last two parameters are
19、 self-explanatory, allowing you to include a specific username and password. void send(content): This method actually makes the request to the server. If the request was declared as asynchronous, this method returns immediately, otherwise it waits until the response is received. The optional argumen
20、t can be an instance of a DOM object, an input stream, or a string. The content passed to this method is sent as part of the request body. void setRequestHeader(string header, string value): This method sets a value for a given header value in the HTTP request. It takes a string representing the hea
21、der to set and a string representing the value to place in the header. Note that it must be called after a call to open(). Of all these methods, the two you will use the most are open() and send(). The XMLHttpRequest object has a number of properties that prove themselves quite useful while designin
22、g Ajax interactions. void abort(): This method is really quite self-explanatory it stops the request. string getAllResponseHeaders(): The core functionality of this method should be familiar to Web application developers it returns a string containing response headers from the HTTP request. Headers include Content-Length, Date, and URI.