AJAX - The Complete Reference

(avery) #1

82 Part I: Core Ideas


Then, like the previous asynchronous example, a callback function must be registered,
but this time when initiating the request using the send() method, pass the payload data as
a parameter to the method.

xhr.send("rating=5");

The previous example’s sendRequest function is now easily modified using the POST method:

function sendRequest(url, payload)
{
var xhr = createXHR();
if (xhr)
{
xhr.open("POST",url,true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function(){handleResponse(xhr);};
xhr.send(payload);
}
}

An example of XHR-based POST requests in action can be found at http://ajaxref.com/
ch3/post.html.

NNOT EOTE While most likely all POST requests will be set to use application/x-www-form-
urlencoded content encoding, it is possible to set just about any desired encoding method.
Chapter 4 will present an in-depth discussion of many possible request and response data formats
and their use with XHRs.

Request Headers


One thing that was sorely missing from the traditional JavaScript communication methods
was the ability to control requests; particularly, setting any needed headers. As seen in the
previous POST example, XHRs provide a method setRequestHeader() to do just that.
The basic syntax is like so:

xhr.setRequestHeader("header-name", "header-value");

where header-name is a string for the header to transmit and header-value a string for the
corresponding value. Both standard and custom headers can be set with this method.
Following HTTP conventions, when setting custom headers, the header would typically be
prefixed by an “X-”. For example, here a header that indicates the JavaScript transport
scheme used is set to show an XHR was employed.

xhr.setRequestHeader("X-JS-Transport", "XHR");

The setRequestHeader() method can be used multiple times and, when behaving
properly, it should append values.

xhr.setRequestHeader("X-Client-Capabilities", "Flash");
xhr.setRequestHeader("X-Client-Capabilities", "24bit-color");

// Header should be X-Client-Capabilities: Flash, 24bit-color
Free download pdf