Ajax 中要用到XMLHttp对象,我见过各种获取该对象的写法,觉得该写法最优雅。首先考虑到了适合不同的浏览器;其次考虑到了优先加载次序,从高版本向低版本试探,最后若还没找到,则抛出异常。
function FactoryXMLHttpRequest() {
if(window.XMLHttpRequest) {
return new XMLHttpRequest();
}else if(window.ActiveXObject) {
var msxmls = new Array(
'Msxml2.XMLHTTP.5.0',
'Msxml2.XMLHTTP.4.0',
'Msxml2.XMLHTTP.3.0',
'Msxml2.XMLHTTP',
'Microsoft.XMLHTTP');
for (var i = 0; i msxmls.length; i++) {
try {
return new ActiveXObject(msxmls[i]);
} catch (e) {
}
}
}
throw new Error("Could not instantiate XMLHttpRequest");
}