AJAX - The Complete Reference

(avery) #1

194 Part II: Applied Ajax^


headers.push({name: "User-Agent", value: "SuperBrowser 14.5"});
options.headers = headers;

Typically, if a header value is set multiple times, a single header is sent with each value
separated by a comma. This works for most things except for cookies. If you look closely
at the code in _makeRequest(), it takes care of these details as it decodes the passed
header array.

/* set user defined headers */
request.headerObj = {};
for (var i=0; i<request.headers.length;i++)
{
if (request.headers[i].name.toUpperCase() == "COOKIE")
document.cookie = request.headers[i].value;
else if(request.headerObj[request.headers[i].name] === undefined)
request.headerObj[request.headers[i].name] = request.headers[i].value;
else
request.headerObj[request.headers[i].name] =
request.headers[i].value + "," + request.headerObj[request.headers[i].name];
}

for (var header in request.headerObj)
request.xhr.setRequestHeader(header, request.headerObj[header]);

NNOT EOTE As discussed in Chapter 3, there are limitations to what headers will actually be set based
both upon specification and the quirks of various browsers.

The last feature from Chapter 3 that was common to all browsers was the XHR’s abort()
method. The library provides a basic method AjaxTCR.comm.abortRequest(requestObj)
that will abort any request indicated in the requestObj parameter. It is important to use this
method rather than the raw XHR method, as it sets the various flags and removes active
progress indications.

NNOT EOTE We avoid using HTTP authentication in the library for now. We doubt the value of including
it in the library based upon the findings in Chapter 3 as well as what you will see in Chapter 7.
We also observe that many popular libraries have made the same decision.

AjaxTCR Library Utility Functions


In order to be able to write Ajax-oriented JavaScript easily, you may find that you are quite
hampered if you stick solely with the standard DOM methods provided. This point should
be pretty clear already if you note how many times we resort to using innerHTML rather
than calling createElement() numerous times. You also saw in Chapter 4 how even the
ever faithful document.getElementById() could use a hand when used with Ajax. Most
popular libraries understand many of the common headaches JavaScript developers might
encounter and have aimed to mitigate them with useful helper functions. We do the same
but try to avoid making massive changes that would change the way JavaScript acts.
Free download pdf