实例化 XMLHttpRequest 对象的最佳方法

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

What is the best method for creating an XMLHttpRequest object?

它应该适用于所有支持的浏览器.

It should work in all capable browsers.

推荐答案

对于无库的解决方案,您可以很容易地模拟 Prototype 对 Try.these 的使用:

For a library-less solution, you can emulate Prototype's use of Try.these fairly easily:

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;
}

相关文章