How Ajax handles the compatibility of Firefox or other non-IE browsers

Source: Internet
Author: User
Tags object

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.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.