If you choose a browser other than Internet Explorer, or you write code for a non-Microsoft browser, you need to use different code. In fact, this is the simple line of code shown in Listing 1:
var xmlHttp = new XMLHttpRequest object;.
This much simpler code creates the XMLHttpRequest object in Mozilla, Firefox, Safari, Opera, and virtually all non-Microsoft browsers that support Ajax in any form or mode.
Combined
The key is to support all browsers. Who would like to write an application that can only be used for Internet Explorer or non-Microsoft browsers? Or worse, write an application two times? So code should support both Internet Explorer and non-Microsoft browsers. Listing 4 shows such a code.
Listing 4. Create a XMLHttpRequest object in a variety of browser-enabled ways
/* Create A new XMLHttpRequest object to talk to the WEB server * *
var xmlHttp = false;
/* @cc_on @*/
/* @if (@_jscript_version >= 5)
try {
XmlHttp = new ActiveXObject ("Msxml2.xmlhttp");
catch (e) {
try {
XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
} catch (E2) {
XmlHttp = false;
}
}
@end @*/
if (!xmlhttp && typeof xmlhttprequest!= ' undefined ') {
XmlHttp = new XMLHttpRequest ();
}
Now, regardless of the strange symbols that are commented out, such as @cc_on, this is a special JavaScript compiler command. The core of this piece of code is divided into three steps:
1. Establish a variable XMLHTTP to refer to the XMLHttpRequest object that is about to be created.
2. Try to create the object in a Microsoft browser:
o Try to create it using the Msxml2.xmlhttp object.
o if it fails, try microsoft.xmlhttp the object again.
3. If XMLHTTP is still not established, the object is created in a non-Microsoft way.
Finally, XMLHTTP should refer to a valid XMLHttpRequest object, no matter what browser is running.