实例化XMLHttpRequest对象的最佳方法

use*_*886 7 javascript ajax xmlhttprequest cross-browser

创建XMLHttpRequest对象的最佳方法是什么?

它应该适用于所有有能力的浏览器.

Jon*_*ski 11

对于无库的解决方案,您可以Try.these非常轻松地模拟Prototype的使用:

function newAjax() {
    try { return new XMLHttpRequest();                    } catch(){}
    try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(){}
    try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(){}
    try { return new ActiveXObject('Msxml2.XMLHTTP');     } catch(){}
    try { return new ActiveXObject('Microsoft.XMLHTTP');  } catch(){}
    return false;
}
Run Code Online (Sandbox Code Playgroud)


use*_*612 9

这是一个有用的链接和一些代码(应涵盖所有基础)

http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx

        var request = null;

        function InitAJAX()
        {
            var objxml = null;
            var ProgID = ["Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.3.0", "Microsoft.XMLHTTP"];            

            try
            {
                objxml = new XMLHttpRequest();
            }
            catch(e)
            {                
                for (var i = 0; i < ProgID.length; i++)
                {
                    try
                    {
                        objxml = new ActiveXObject(ProgID[i]);
                    }
                    catch(e)
                    {                        
                        continue;
                    }
                }
            }

            return objxml;            
        }

        request = InitAJAX();
Run Code Online (Sandbox Code Playgroud)

  • @Bishiboosh - 在Firefox中工作正常 - https://developer.mozilla.org/En/Using_XMLHttpRequest (2认同)

cle*_*tus 8

使用jQuery(或类似的JavaScript库).它负责处理Ajax调用之类的跨浏览器兼容性问题.

例如,使用jQuery Ajax调用:

$.ajax({
    url: 'document.xml',
    type: 'GET',
    dataType: 'xml',
    timeout: 1000,
    error: function(){
        alert('Error loading XML document');
    },
    success: function(xml){
        // do something with xml
    }
});
Run Code Online (Sandbox Code Playgroud)


Chr*_*oph 8

我建议跟随谢尔盖的建议,或者自己为IE编写一个不太复杂的小补丁:

if(typeof window.XMLHttpRequest === 'undefined' &&
    typeof window.ActiveXObject === 'function') {
    window.XMLHttpRequest = function() {
        try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
        try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
        return new ActiveXObject('Microsoft.XMLHTTP');
    };
}
Run Code Online (Sandbox Code Playgroud)

那你可以做

var req = new XMLHttpRequest;
Run Code Online (Sandbox Code Playgroud)

甚至在IE中.

编辑2011-02-18:请参阅此博文,了解新选择的MSXML版本背后的理由......