检索跨浏览器XmlHttpRequest的最简单方法

检索适用于所有浏览器的XmlHttpRequest对象的最简单,最安全的方法是什么?没有任何额外的库。您经常使用一个代码段吗?


PS:我知道网上有很多例子,但这恰恰是我要问的原因:例子太多了,我只想简单实用的东西来工作。



杨__羊羊
浏览 491回答 3
3回答

HUWWW

根据要求,简单且行之有效: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;}

凤凰求蛊

不确定您的问题是否100%-但是,如果您要返回跨浏览器XMLHTTP实例的函数-我们在本机ajax库中使用此方法已有多年了-在任何浏览器中都没有问题function getXMLHTTP() {&nbsp; &nbsp; var alerted;&nbsp; &nbsp; var xmlhttp;&nbsp; &nbsp; /*@cc_on @*/&nbsp; &nbsp; /*@if (@_jscript_version >= 5)&nbsp; &nbsp; // JScript gives us Conditional compilation, we can cope with old IE versions.&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")&nbsp; &nbsp; } catch (e) {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")&nbsp; &nbsp; } catch (E) {&nbsp; &nbsp; &nbsp; &nbsp; alert("You must have Microsofts XML parsers available")&nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; @else&nbsp; &nbsp; &nbsp; &nbsp; alert("You must have JScript version 5 or above.")&nbsp; &nbsp; &nbsp; &nbsp; xmlhttp=false&nbsp; &nbsp; &nbsp; &nbsp; alerted=true&nbsp; &nbsp; @end @*/&nbsp; &nbsp; if (!xmlhttp && !alerted) {&nbsp; &nbsp; &nbsp; &nbsp; // Non ECMAScript Ed. 3 will error here (IE<5 ok), nothing I can&nbsp; &nbsp; &nbsp; &nbsp; // realistically do about it, blame the w3c or ECMA for not&nbsp; &nbsp; &nbsp; &nbsp; // having a working versioning capability in&nbsp; <SCRIPT> or&nbsp; &nbsp; &nbsp; &nbsp; // ECMAScript.&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; xmlhttp = new XMLHttpRequest();&nbsp; &nbsp; &nbsp; &nbsp; } catch (e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("You need a browser which supports an XMLHttpRequest Object")&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return xmlhttp}
打开App,查看更多内容
随时随地看视频慕课网APP