Main Page

post() method

setTimeout(function () {
fnCallback(httpGet(sURL));
}, 10);
} else {
alert(“Your browser doesn’t support HTTP requests.”);
}
};
With this completed, it’s now possible to send a GET request using common code in a variety of
browsers:
var sURL = “http://www.somewhere.com/page.php”;
sURL = addURLParam(sURL, “name”, “Nicholas”);
sURL = addURLParam(sURL, “book”, “Professional JavaScript”);
Http.get(sURL, function(sData) {
alert(“Server sent back: “ + sData);
});
Remember, because LiveConnect requires you to enter the full URL for the request, you must always
supply the full URL with the
Http.get()
method, just in case the browser uses LiveConnect.
The post() method
The
post()
method works similarly to the
get()
method, except it needs three arguments: the URL, the
parameters string, and the callback function. For simplicity’s sake, a callback function for
post()
uses
the same format as the one used for
get()
.
The method itself is also remarkably similar to
get()
, using the same
if..else
statements. The only
differences are the setting of the request header, the number of arguments, and the fact that the method
sends a POST request instead of a GET. Here’s the method:
Http.post = function (sURL, sParams, fnCallback) {
if (bXmlHttpSupport) {
var oRequest = new XMLHttpRequest();
oRequest.open(“post”, sURL, true);
oRequest.setRequestHeader(“Content-Type”,
“application/x-www-form-urlencoded”);
oRequest.onreadystatechange = function () {
if (oRequest.readyState == 4) {
fnCallback(oRequest.responseText);
}
}
oRequest.send(sParams);
} else if (navigator.javaEnabled() && typeof java != “undefined”
&& typeof java.net != “undefined”) {
setTimeout(function () {
fnCallback(httpPost(sURL, sParams));
505
Client-Server Communication
19_579088 ch16.qxd 3/28/05 11:42 AM Page 505


JavaScript EditorFree JavaScript Editor     Ajax Editor


©