Main Page

LiveConnect Requests

It also helps to have a function for formatting the parameters for a POST request:
function addPostParam(sParams, sParamName, sParamValue) {
if (sParams.length > 0) {
sParams += “&”;
return sParams + encodeURIComponent(sParamName) + “=”
+ encodeURIComponent(sParamValue);
This function is similar to the
function, although
deals with a string
of parameters instead of a URL. The first argument is the existing list of parameters, the second argu-
ment is the parameter name, and the third is the parameter value. The function checks whether the
length of the parameters string is longer than
. If so, then it adds an ampersand to separate the new
parameter. Otherwise, it returns the parameter string with the new name and value added. Here’s a brief
example of its use:
var sParams = “”;
sParams = addPostParam(sParams, “name”, “Nicholas”);
sParams = addPostParam(sParams, “book”, “Professional JavaScript”);“post”, “page.php”, false);
Even though this looks like a valid POST request, a server-side page expecting a POST actually won’t
interpret this code correctly. That’s because all POST requests sent by a browser have the
header set to
. Fortunately, that can be easily cor-
rected using the
var sParams = “”;
sParams = addPostParam(sParams, “name”, “Nicholas”);
sParams = addPostParam(sParams, “book”, “Professional JavaScript”);“post”, “page.php”, false);
oRequest.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);
Now this example works just like a form POSTed from a Web browser.
LiveConnect Requests
Netscape Navigator introduced a concept called
, a capability that enables JavaScript to inter-
act with and use Java classes. To work, the user must have a Java Runtime Environment (JRE) installed,
and Java must be enabled in the browser. Almost all modern browsers (with Internet Explorer being the
major exception) support LiveConnect, which provides access to all the HTTP-related libraries that Java
Performing a GET request
If you know how to perform a GET request using Java, it’s very easy to convert the request into a
LiveConnect script. The first step is to create a new instance of
Chapter 16
19_579088 ch16.qxd 3/28/05 11:42 AM Page 498

JavaScript EditorFree JavaScript Editor     Ajax Editor