Initiating a Request to the Server
When users click the
Submit Query button on the form in
Figure 2, the JavaScript function invokes the
callService function, which makes a request to the server via the XMLHttpRequest object. I'll discuss the XMLHttpRequest object in more detail below, but first, observe the HTML form:
<form name="ServiceRequestForm"
method="POST" onSubmit="return false">
<table>
<tr>
<td>
<textarea name="result"
id="result"
COLS="40"
ROWS="8">
</textarea>
</td>
<td>
<textarea name="users"
id="users"
COLS="20"
ROWS="8">
</textarea>
</td>
</tr>
<tr>
<td colspan="2">
<input name="submit"
id="submit"
type="submit"
onclick="callService(" +
"'services?ServiceName=' +
'TestUserAccountService&ServiceParams=');">
<input name="reset"
id="reset"
type="reset"
onclick="resetFields();">
</td>
</tr>
</table>
</form>
Notice that the code invokes the JavaScript function
callService when the user presses the Submit button. This function makes a request to the FrontController URL via the XMLHttpRequest object. The
callService function is as follows:
var httpObj;
var isWorking = false;
function callService(url)
{
if (!isWorking)
{
httpObj.open("GET", url, true);
try
{
httpObj.setRequestHeader("Content-type",
"text/plain");
}
catch(e)
{
// setRequestHeader not in some Opera versions
}
isWorking = true;
httpObj.onreadystatechange =
handleServiceResponse;
httpObj.send(null);
return true;
}
}
The
open method of the XMLHttpRequest object in the preceding function takes three parameters:
- A string defining the HTTP method (GET, POST, etc.) to call.
- The URL to which to direct the call.
- A Boolean that controls whether the call should be made synchronously or asynchronously.
The
callService function handles duties for object creation, event handler assignment, and submission of an HTTP
GET request via the XMLHttpRequest's
open method. The
callService function assumes that the global variable
httpObj has been previously instantiated and that a JavaScript callback function named
handleServiceResponse exists that will handle changes to the state of the XMLHttpRequest object.