Google

Saturday, May 24, 2008

Using the XMLHttpRequest Object

As mentioned, the XMLHttpRequest object is the heart of AJAX. This object sends requests
to the server and processes the responses from it. In versions of Internet Explorer prior
to IE7, it is implemented using ActiveX, whereas in other browsers, such as Mozilla
Firefox, Safari, Opera, and Internet Explorer 7, it is a native JavaScript object. Unfortunately,
because of these differences, you need to write JavaScript code that inspects the
browser type and creates an instance of it using the correct technology.
Thankfully, this process is a little simpler than the spaghetti code you may remember
having to write when using JavaScript functions that heavily used DOM, which had to
work across browsers:
var xmlHttp;
function createXMLHttpRequest()
{
if (window.ActiveXObject)
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
xmlHttp = new XMLHttpRequest();
}
}
In this case, the code is simple. If the browser doesn’t support ActiveX objects, the
window.ActiveXObject property will be null, and, therefore, the xmlHttp variable will be set
to a new instance of the native JavaScript XMLHttpRequest object; otherwise, a new
instance of the Microsoft.XMLHTTP ActiveX Object will be created.
Now that you have an XMLHttpRequest object at your beck and call, you can start
playing with its methods and properties. Some of the more common methods you can
use are discussed in the next few paragraphs.
The open method initializes your request by setting up the call to your server. It takes
two required arguments (the Hypertext Transfer Protocol [HTTP] command such as GET,
POST, or PUT, and the URL of the resource you are calling) and three optional arguments
(a boolean indicating whether you want the call to be asynchronous, which defaults to
true, and strings for the username and password if required by the server for security).
It returns void.

No comments: