AJAX - The Complete Reference

(avery) #1

Chapter 3: XMLHttpRequest Object 97


PART I


Response Headers


XHRs have two methods to read response headers: getResponseHeader(headername)
and getAllResponseHeaders(). As soon as the XHR has reached readyState 3, it
should be possible to look at the response headers that have been returned by the server.
Here are two simple examples:

xhr.getResponseHeader("Content-Length"); // fetches a single header
xhr.getAllResponseHeaders(); // fetches all the headers

Some possible values are shown next:

Both methods return strings, but note that in the case of multiple headers, the results will
contain \n for newlines.

If you plan on placing the headers in an XHTML page, you will have to convert the \n to
break tags or use some other preformatting mechanism to output them nicely to the screen.

var allHeaders = xhr.getAllResponseHeaders();
allHeaders = allHeaders.replace(/\n/g, "<br/>");

Looking at edge cases, there are only minor variations in browsers. For example,
attempting to fetch a header that does not exist with getResponseHeader(), may result in
a slight difference in what is returned. Firefox returns null, while IE returns nothing. Given
the loose typing system of JavaScript, this difference likely won’t be noted. Both browsers
agree what to do when you attempt to invoke these methods before headers are available:
throw a JavaScript error.

Controlling Requests


The XMLHttpRequest object has fairly limited ability to control requests once they’re sent
outside the abort() method. This method provides the basic functionality of the stop button
in the browser and will very likely be used in your Ajax applications to address network
timeouts. For example, you might imagine that you can write a cancelRequest() function
Free download pdf