Datasheet

Chapter 1: AJAX Technologies
12
Next, submitCallback assigns a reference, which references a JavaScript function named
readyStateChangeCallback, to the onreadystatechange property of the XMLHttpRequest object:
request.onreadystatechange = readyStateChangeCallback;
Then, it invokes the setRequestHeader method on the XMLHttpRequest object to add a custom header
named
MyCustomHeader with the value true :
request.setRequestHeader(“MyCustomHeader”, “true”);
As you’ll see later, when the page finally posts back to itself, the server-side code uses this header to dis-
tinguish between ansynchronous and normal synchronous postback requests.
Next, the
submitCallback function invokes the setRequestHeader method again, this time to set the
value of the
Content-Type header request to application/x-www-form-urlencoded :
request.setRequestHeader(‘Content-Type’, ‘application/x-www-form-urlencoded’);
As you’ll see later, this will allow you to use the Request object to access the posted data.
Finally,
submitCallback invokes the send method on the XMLHttpRequest object, passing in the string
that contains the post data to make an HTTP
POST request to the server:
request.send(body);
As previously discussed, this string is the return value of the serialize method.
Now let’s walk through the implementation of the
serialize function:
function serialize(credentials)
{
var requestBody=””;
requestBody += “usernametbx”;
requestBody += “=”;
requestBody += encodeURIComponent(credentials.username);
requestBody += “&”;
requestBody += “passwordtbx”;
requestBody += “=”;
requestBody += encodeURIComponent(credentials.password);
return requestBody;
}
The serialize function generates a string that consists of two substrings separated by the &
character. The first substring itself consists of two substrings separated by the equal sign (
= ), where
the first substring contains the
name HTML attribute value of the username text box DOM element
and the second substring contains the value that the end user has entered into this text box:
var requestBody = ””;
requestBody += “usernametbx”;
requestBody += “=”;
requestBody += usernametbx.value;
c01.indd 12c01.indd 12 8/20/07 5:40:07 PM8/20/07 5:40:07 PM