Main Page

HTTP Requests

HTTP Requests
In many modern browsers, it’s possible to initiate HTTP requests directly from JavaScript and get the
result back in JavaScript, completely eliminating the need for hidden frames and other such trickery.
At the center of this exciting new capability is an object Microsoft created called the XML HTTP request.
This object came along with MSXML but wasn’t fully explored until recently. Essentially, an XML HTTP
request is a regular HTTP request with added functionality for sending and receiving XML code.
To create a new XML HTTP request in Internet Explorer, you must once again use an
ActiveXObject
:
var oRequest = new ActiveXObject(“Microsoft.XMLHTTP”);
Like the XML DOM in IE, the XML HTTP request object has multiple versions, so a function is necessary
to make sure you’re using the most recent one:
function createXMLHTTP() {
var arrSignatures = [“MSXML2.XMLHTTP.5.0”, “MSXML2.XMLHTTP.4.0”,
“MSXML2.XMLHTTP.3.0”, “MSXML2.XMLHTTP”,
“Microsoft.XMLHTTP”];
for (var i=0; i < arrSignatures.length; i++) {
try {
var oRequest = new ActiveXObject(arrSignatures[i]);
return oRequest;
} catch (oError) {
//ignore
}
}
throw new Error(“MSXML is not installed on your system.”);
}
After you have created it, you can use the
open()
method to specify the request to send. This method
takes three arguments: the type of request to send (GET, POST, or any other HTTP method supported by
the server); the URL of the request; and a Boolean indicating whether the request should be sent asyn-
chronously or not (the same as you do with the XML DOM
load()
method). For example:
oRequest.open(“get”, “example.txt”, false);
After opening the request, you must send it by using the
send()
method. This method always requires
an argument, which can be
null
most of the time:
oRequest.send(null);
If you choose to make the request synchronously (setting the third argument to
false
), the JavaScript
interpreter waits for the request to return. When the response comes back, it fills the
status
property
493
Client-Server Communication
19_579088 ch16.qxd 3/28/05 11:42 AM Page 493


JavaScript EditorFree JavaScript Editor     Ajax Editor


©