3 回答
TA贡献1874条经验 获得超12个赞
根据要求,简单且行之有效:
function Xhr(){ /* returns cross-browser XMLHttpRequest, or null if unable */
try {
return new XMLHttpRequest();
}catch(e){}
try {
return new ActiveXObject("Msxml3.XMLHTTP");
}catch(e){}
try {
return new ActiveXObject("Msxml2.XMLHTTP.6.0");
}catch(e){}
try {
return new ActiveXObject("Msxml2.XMLHTTP.3.0");
}catch(e){}
try {
return new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){}
try {
return new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
return null;
}
将其折叠成一行,我们得到:
function Xhr(){
try{return new XMLHttpRequest();}catch(e){}try{return new ActiveXObject("Msxml3.XMLHTTP");}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0");}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0");}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP");}catch(e){}try{return new ActiveXObject("Microsoft.XMLHTTP");}catch(e){}return null;
}
TA贡献1825条经验 获得超4个赞
不确定您的问题是否100%-但是,如果您要返回跨浏览器XMLHTTP实例的函数-我们在本机ajax库中使用此方法已有多年了-在任何浏览器中都没有问题
function getXMLHTTP() {
var alerted;
var xmlhttp;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
try {
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
} catch (E) {
alert("You must have Microsofts XML parsers available")
}
}
@else
alert("You must have JScript version 5 or above.")
xmlhttp=false
alerted=true
@end @*/
if (!xmlhttp && !alerted) {
// Non ECMAScript Ed. 3 will error here (IE<5 ok), nothing I can
// realistically do about it, blame the w3c or ECMA for not
// having a working versioning capability in <SCRIPT> or
// ECMAScript.
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
alert("You need a browser which supports an XMLHttpRequest Object")
}
}
return xmlhttp
}
- 3 回答
- 0 关注
- 490 浏览
相关问题推荐
添加回答
举报