Main Page

Performing a POST request

http://www.somewhere.com/page.php?name1=value1&name2=value2&name3=value3
Each name and value must be encoded for use in a URL (in JavaScript, this can be done using
encodeURIComponent()
). 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
pages.
To send a GET request using the XML HTTP request object, just place the URL (with all parameters) into
the
open()
method and make sure this first argument is
“get”
:
oRequest.open(“get”, “http://www.somewhere.com/page.php?name1=value1”, 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;
}
The
addURLParam()
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 = “http://www.somwhere.com/page.php”;
sURL = addURLParam(sURL, “name”, “Nicholas”);
sURL = addURLParam(sURL, “book”, “Professional JavaScript”);
oRequest.open(“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
send()
method:
oRequest.open(“post”, “page.php”, false);
oRequest.send(“name1=value1&name2=value2”);
497
Client-Server Communication
19_579088 ch16.qxd 3/28/05 11:42 AM Page 497


JavaScript EditorFree JavaScript Editor     Ajax Editor


©