↑
Main Page
XML HTTP request
function callback_function(sData) {
//interpret data here
}
The callback function is passed the data retrieved from the HTTP request as its only argument,
sData
.
You are then free to do as you please with the result. In order to use the callback function, you must con-
sider a couple of details.
First, when using the XML HTTP request object to perform a GET, it’s easy to set up a callback function
by using an asynchronous request and calling the function when the
readyState
is equal to
4
:
Http.get = function (sURL, fnCallback) {
if (bXmlHttpSupport) {
var oRequest = new XMLHttpRequest();
oRequest.open(“get”, sURL, true);
oRequest.onreadystatechange = function () {
if (oRequest.readyState == 4) {
fnCallback(oRequest.responseText);
}
}
oRequest.send(null);
}
//...
};
This section of code uses JavaScript closures to allow the callback function,
fnCallback
, to be used in
the
onreadystatechange
event handler. Because
fnCallback
is just a function, it’s called like any
other function and passed the
responseText
of the request when
readyState
is
4
.
If there is no support for the XML HTTP request, you must check whether LiveConnect is enabled.
Unfortunately, no property or setting indicates whether LiveConnect can be used. The only way to tell is
to ensure that Java is enabled in the browser by using the
navigator.javaEnabled()
method and
determine whether the type of
java
and
java.net
are not undefined:
Http.get = function (sURL, fnCallback) {
if (bXmlHttpSupport) {
var oRequest = new XMLHttpRequest();
oRequest.open(“get”, sURL, true);
oRequest.onreadystatechange = function () {
if (oRequest.readyState == 4) {
fnCallback(oRequest.responseText);
}
}
oRequest.send(null);
503
Client-Server Communication
19_579088 ch16.qxd 3/28/05 11:42 AM Page 503
Free JavaScript Editor
Ajax Editor
©
→