Main Page

createXMLHTTP

with the HTTP status of the request (200 is good, 404 means the page wasn’t found, and so on). It also
fills the
statusText
property with a message describing the status and the
responseText
property
with the text received back from the server. Additionally, if the text is XML, it fills the
responseXML
property, which is an XML DOM object constructed from the returned text. For example:
var oRequest = createXMLHTTP();
oRequest.open(“get”, “example.txt”, false);
oRequest.send(null);
alert(“Status is “ + oRequest.status + “ (“ + oRequest.statusText + “)”);
alert(“Response text is: “ + oRequest.responseText);
This example gets a plain text file and displays its contents. The
status
and
statusText
are also
displayed.
Requesting an XML file also fills the
responseXML
property:
var oRequest = createXMLHTTP();
oRequest.open(“get”, “example.xml”, false);
oRequest.send(null);
alert(“Status is “ + oRequest.status + “ (“ + oRequest.statusText + “)”);
alert(“Response text is: “ + oRequest.responseText);
alert(“Tag name of document element is: “ +
oRequest.responseXML.documentElement.tagname);
This example shows the tag name of the document element loaded into the
responseXML
property.
If you decide to send an asynchronous request, you must use the
onreadystatechange
event handler
to see when the
readyState
property is equal to
4
(the same as with the XML DOM). All the same
properties and methods are used, with the slight alteration that the response properties can’t be used
until the request has completed:
var oRequest = createXMLHTTP();
oRequest.open(“get”, “example.txt”, true);
oRequest.onreadystatechange = function () {
if (oRequest.readyState == 4) {
alert(“Status is “ + oRequest.status + “ (“ + oRequest.statusText + “)”);
alert(“Response text is: “ + oRequest.responseText);
}
}
oRequest.send(null);
This example doesn’t work when run locally: It must be run on a server because the
XML HTTP object relies on the server-reported mime type to determine if the
requested file is an XML document.
If you run this example locally, the
status
is
0
and the
statusText
is
“Unknown”
because a local file read isn’t an actual HTTP request.
494
Chapter 16
19_579088 ch16.qxd 3/28/05 11:42 AM Page 494


JavaScript EditorFree JavaScript Editor     Ajax Editor


©