Main Page

Using headers

As in the synchronous calls, the
status
,
statusText
, and
responseText
properties are filled with data.
With asynchronous calls, it’s possible to cancel the request altogether by calling the
abort()
method
before the
readyState
reaches
4
:
var oRequest = createXMLHTTP();
oRequest.open(“get”, “example.txt”, true);
oRequest.onreadystatechange = function () {
if (oRequest.readyState == 3) {
oRequest.abort();
} else if (oRequest.readyState == 4) {
alert(“Status is “ + oRequest.status + “ (“ + oRequest.statusText + “)”);
alert(“Response text is: “ + oRequest.responseText);
}
}
oRequest.send(null);
In this example, the alerts are never displayed because the request is aborted when
readyState
is
3
.
Using headers
Every HTTP request sends along with it a group of headers with additional information. In everyday
browser use, these headers are hidden because they aren’t needed by the end user. However, these head-
ers can be quite necessary to developers, and so the XML HTTP request object provides methods to get
and set them.
The first is a method called
getAllResponseHeaders()
, which returns a string containing all the
headers attached to the response. Here’s a sample of the type of information returned by
getAllResponseHeaders()
:
Date: Sun, 14 Nov 2004 18:04:03 GMT
Server: Apache/1.3.29 (Unix)
Vary: Accept
X-Powered-By: PHP/4.3.8
Connection: close
Content-Type: text/html; charset=utf-8
From this header information, you can tell that the server is running Apache on Unix with PHP support
and the file being returned is an HTML file. If you want to retrieve only one of the headers, you can use
the
getResponseHeader()
method with the name of header to retrieve. For example, to retrieve the
value of the
“Server”
header, you can do this:
var sValue = oRequest.getResponseHeader(“Server”);
Reading request headers is just part of the equation; the other part is setting your own headers on the
request before it’s sent.
Using the
setRequestHeader()
method, you can set headers on the XML HTTP request before it’s sent
out. For example:
oRequest.setRequestHeader(“myheader”, “yippee”);
oRequest.setRequestheader(“weather”, “warm”);
495
Client-Server Communication
19_579088 ch16.qxd 3/28/05 11:42 AM Page 495


JavaScript EditorFree JavaScript Editor     Ajax Editor


©