↑
Main Page
Intelligent HTTP Requests
oConnection.setRequestProperty(“Content-Type”,
“application/x-www-form-urlencoded”);
var oOutput = new java.io.DataOutputStream(oConnection.getOutputStream());
oOutput.writeBytes(sParams);
oOutput.flush();
oOutput.close();
var sLine = “”, sResponseText = “”;
var oInput = new java.io.DataInputStream(oConnection.getInputStream());
sLine = oInput.readLine();
while (sLine != null){
sResponseText += sLine + “\n”;
sLine = oInput.readLine();
}
oInput.close();
return sResponseText;
}
Using this function, you can submit a POST request like the following:
var sParams = “”;
sParams = addPostParam(sParams, “name”, “Nicholas”);
sParams = addPostParam(sParams, “book”, “Professional JavaScript”);
var sData = httpPost(“http://www.somewere.com/reflectpost.php”,sParams);
Intelligent HTTP Requests
With two completely different ways of doing HTTP requests, it’s helpful to have a common set of func-
tions to avoid headaches. First, you determine whether you can use the XML HTTP request object or not.
To check, see if the type of
XMLHttpRequest
is equal to
“object”
or if
window.ActiveXObject
is
valid:
var bXmlHttpSupport = (typeof XMLHttpRequest == “object” || window.ActiveXObject);
Next, create a placeholder object named
Http
to contain the methods:
var Http = new Object;
The get() method
The first method is called, simply,
get()
, and its purpose is to perform a GET request on a specific URL.
This method has two arguments: the URL to send the request to and a callback function. Callback func-
tions are used in many programming languages to notify the developer when a request has concluded.
For the
get()
method, the callback function has the following format:
502
Chapter 16
19_579088 ch16.qxd 3/28/05 11:42 AM Page 502
Free JavaScript Editor
Ajax Editor
©
→