Most AJAX frameworks obtain an instance of the XMLHttpRequest object for the current
browser using code that looks like the following:
var xmlRequest, e;
try {
xmlRequest = new XMLHttpRequest();
}
catch(e) {
try {
xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
}
}
The code first tries to instantiate the internal XMLHttpRequest object and opts for the ActiveX
object in the case of failure. As you can see, the creation of the object requires an exception to
be caught when the browser is Internet Explorer 6.0 or any older versions. Such a code will
work unchanged (and won’t require any exception) in Internet Explorer 7.0.
Note : Checking the browser’s user agent and foregoing the exception is fine as well.
However, ASP.NET AJAX Extensions uses the preceding code because it makes the overall
library independent from details of user agent strings and browser details. In this way, you do
“object detection” instead of “browser detection.” The final result, though, is the same. The
exception is fired only if the browser is Internet Explorer older than version 7.0 or any other
browser that doesn’t support AJAX functionalities. If you’re building your own AJAX framework,
you need to check the user agent only against Internet Explorer.
The open method prepares the channel for the request; no physical socket is created yet,
though. To execute a POST statement, you need to add the proper content-type header. The
Boolean argument indicates whether the operation is asynchronous:
xmlRequest.open("POST", url, false);
xmlRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlRequest.send(postData);
The send method opens the socket and sends the packet. In the preceding code snippet, the
method returns only when the response has been fully received.
An asynchronous request requires slightly different code:
xmlRequest.open("POST", url, true);
xmlRequest.onreadystatechange = CallbackComplete;
xmlRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlRequest.send(postData);
The CallbackComplete element is a placeholder for a JavaScript function that retrieves and processes the response generated by the request.
Note : that the function assigned to the onreadystatechange member will be invoked whenever
readyState changes value. Possible values for the state are the integers ranging from 0 through
4, which mean “Uninitialized,” “Open method called successfully,” “Send method called successfully,”
“Receiving data,” and “Response received,” respectively. The CallbackComplete
framework-specific function will generally check that state and proceed.