Chapter 3: XMLHttpRequest Object 83
PART I
As shown in the previous section, the most likely known HTTP headers, particularly the
Content-Type header, will be needed when posting data.
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
This method is also useful with GET requests to set headers to influence cache control in
browsers that inappropriately (or appropriately) cache XHR requests. This directive can be
performed on the client side by setting the If-Modified-Since HTTP request header to
some date in the past, like so:
xhr.setRequestHeader("If-Modified-Since", "Wed, 15 Nov 1995 04:58:08 GMT");
This is just another common example of the setRequestHeader() method. We will
explore cache control quite a bit in Chapter 6.
Given the previous discussion of custom headers, you might wonder what would
happen if you try to add to or even change headers that maybe you shouldn’t. For example,
can the Referer header be changed to look like the request is coming from another location?
xhr.setRequestHeader("Referer", "http://buzzoff.ajaxref.com");
How about the User-Agent header? Or how about actions that might be useful, like
adding other Accept header values? Unfortunately, you’ll see in the next section that the
belief that XHR support is the same in browsers is not quite all it is cracked up to be.
Request Header Headaches
According to the emerging XMLHttpRequest specification from the W3C, for security
reasons, browsers are supposed to ignore the use of setRequestHeader() for the headers
shown in Table 3-5.
Also, when setting the headers in Table 3-6, the values specified by setRequestHeader()
should replace any existing values.
Finally, all other headers set via this method are supposed to append to the current
value being sent, if defined, or create a new value if not defined. For example, given:
xhr.setRequestHeader("User-Agent", "Ajax Browser ");
data should be added to the existing User-Agent header, not replace it.
While the specification may indicate one thing, the actual support in browsers for setting
headers seems to be, in a word, erratic. For example, the Referer header is sent in XHR
requests by Internet Explorer, Safari, and Opera, but it is not settable as per the specification
by these browsers. However, some versions of Firefox (1.5) do not send the header normally
but do allow you to set it. For other headers, the situation maybe the opposite, with Firefox
Accept-Charset Date TE
Accept-Encoding Host Trailer
Content-Length Keep-Alive Transfer-Encoding
Expect Referer Upgrade
TABLE 3-5 setRequestHeader Values That Should Be Ignored