The most common type of request on the Web is a GET request. Every time you enter a URL into your browser and click Go, you are sending a GET request to a server.
Parameters to a GET request are attached to the end of the URL with a question mark, followed by name/value pairs separated by an ampersand. For example:
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 parametername, 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 questionmark; otherwise, it adds an ampersand. Next, the name and value are encoded and appended to the endof 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.