Document directory
The main point of AJAX is the XMLHttpRequest object.
Different browsers use different methods to create XMLHttpRequest objects.
Use the IE browserActiveXObjectWhile other browsers useXMLHttpRequestJavaScript built-in objects.
To create this object for different browsers, we need to use a "try and catch" statement. You can read more about try and catch statements in our JavaScript tutorial.
Let's use the JavaScript code used to create the XMLHttpRequest object to update our "testAjax.htm" file:
<Html> <body> <script type = "text/javascript"> function ajaxFunction () {varxmlHttp
; Try {// Firefox, Opera 8.0 +, SafarixmlHttp=new XMLHttpRequest();
} Catch (e) {// Internet Explorer try {xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} Catch (e) {try {xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} Catch (e) {alert ("your browser does not support AJAX! "); Return false ;}}}</script> <form name =" myForm "> User: <input type =" text "name =" username "/> time: <input type = "text" name = "time"/> </form> </body> Example:
First, declare an xmlHttp variable that saves the XMLHttpRequest object.
Then use XMLHttp = new XMLHttpRequest () to create this object. This statement is applicable to Firefox, Opera, and Safari browsers. If it fails, try xmlHttp = new ActiveXObject ("Msxml2.XMLHTTP") for Internet Explorer 6.0 +. If it fails, then try xmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ").
If these three methods do not work, the browser used by the user is too outdated. He or she will see a prompt stating that the browser does not support AJAX.
Note: The Code customized by these browsers is long and complex. However, this code can be used whenever you want to create an XMLHttpRequest object, so you can copy and paste the code at any time you need. The above code is compatible with all mainstream browsers: Internet Explorer, Opera, Firefox, and Safari.
The next section shows you how to use the XMLHttpRequest object to communicate with the server.