Main Page

Performing a POST request
Each name and value must be encoded for use in a URL (in JavaScript, this can be done using
). The URL has a maximum size of 2048 characters (2 MB). Everything after
the question mark is referred to as the query string, and these parameters are accessible by server-side
To send a GET request using the XML HTTP request object, just place the URL (with all parameters) into
method and make sure this first argument is
:“get”, “”, false);
Because the parameters must be added to the end of an existing URL, it’s helpful to have a function that
handles all the details:
function addURLParam(sURL, sParamName, sParamValue) {
sURL += (sURL.indexOf(“?”) == -1 ? “?” : “&”);
sURL += encodeURIComponent(sParamName) + “=” + encodeURIComponent(sParamValue);
return sURL;
function takes three arguments: the URL to add the parameters to, the parameter
name, and the parameter value. First, the function checks to see if the URL already contains a question
mark (to determine if other parameters already exist). If it doesn’t, then the function appends a question
mark; otherwise, it adds an ampersand. Next, the name and value are encoded and appended to the end
of the URL. The last step is to return the updated URL.
This function can be used to build up a URL for a request:
var sURL = “”;
sURL = addURLParam(sURL, “name”, “Nicholas”);
sURL = addURLParam(sURL, “book”, “Professional JavaScript”);“get”, sURL, false);
You can then handle the response as usual.
Performing a POST request
The second most common type of HTTP request is a POST. Typically, POST requests are used when
entering data into a Web form because they are capable of sending much more data (around 2 GB) than
GET requests.
Just like a GET request, the parameters for a POST request must be encoded for use in a URL and sepa-
rated with an ampersand, although the parameters aren’t attached to the URL. When sending a POST
request, you pass in the parameters as an argument to the
method:“post”, “page.php”, false);
Client-Server Communication
19_579088 ch16.qxd 3/28/05 11:42 AM Page 497

JavaScript EditorFree JavaScript Editor     Ajax Editor