ajax 检索跨浏览器 XmlHttpRequest 的最简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2557247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Easiest way to retrieve cross-browser XmlHttpRequest
提问by Egor Pavlikhin
What is the easiest and safest way to retrieve XmlHttpRequest object that works across all browsers? Without any extra libraries. Is there a code snippet you use often?
检索适用于所有浏览器的 XmlHttpRequest 对象的最简单和最安全的方法是什么?没有任何额外的库。有没有你经常使用的代码片段?
P.S. I know there are tons of examples on the net, but this is precisely the reason I am asking: there are too many different examples, and I just want something simple and proven to work.
PS我知道网上有很多例子,但这正是我问的原因:有太多不同的例子,我只想要一些简单且行之有效的东西。
jQuery and other libraries is NOT an option.Why does jquery leak memory so badly?
jQuery 和其他库不是一种选择。为什么jquery会如此严重地泄漏内存?
回答by Wolph
While I would recommend using a full library to make usage easier, making AJAX requests can be fairly simple in modern browsers:
虽然我建议使用完整的库来简化使用,但在现代浏览器中发出 AJAX 请求可能相当简单:
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(this.readyState == 4){
alert('Status code: ' + this.status);
// The response content is in this.responseText
}
}
req.open('GET', '/some-url', true);
req.send();
The following snippet is a more advanced snippet based on a snippet from quirksmode.organd even supports very old browsers (older than Internet Explorer 7):
以下代码段是基于quirksmode.org代码段的更高级代码段,甚至支持非常旧的浏览器(比 Internet Explorer 7 旧):
function sendRequest(url,callback,postData) {
var req = createXMLHTTPObject();
if (!req) return;
var method = (postData) ? "POST" : "GET";
req.open(method,url,true);
// Setting the user agent is not allowed in most modern browsers It was
// a requirement for some Internet Explorer versions a long time ago.
// There is no need for this header if you use Internet Explorer 7 or
// above (or any other browser)
// req.setRequestHeader('User-Agent','XMLHTTP/1.0');
if (postData)
req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
req.onreadystatechange = function () {
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304) {
// alert('HTTP error ' + req.status);
return;
}
callback(req);
}
if (req.readyState == 4) return;
req.send(postData);
}
var XMLHttpFactories = [
function () {return new XMLHttpRequest()},
function () {return new ActiveXObject("Msxml3.XMLHTTP")},
function () {return new ActiveXObject("Msxml2.XMLHTTP.6.0")},
function () {return new ActiveXObject("Msxml2.XMLHTTP.3.0")},
function () {return new ActiveXObject("Msxml2.XMLHTTP")},
function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];
function createXMLHTTPObject() {
var xmlhttp = false;
for (var i=0;i<XMLHttpFactories.length;i++) {
try {
xmlhttp = XMLHttpFactories[i]();
}
catch (e) {
continue;
}
break;
}
return xmlhttp;
}
回答by Pacerier
As requested, simple and proven to work:
根据要求,简单且经证明有效:
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;
}
Collapsing it into a single line, we get:
将其折叠成一行,我们得到:
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;
}
回答by plodder
not 100% certain of your question - but if you're asking for function to return a cross browser XMLHTTP instance - we have used this in our native ajax library for years - and never a problem in any browser
不是 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
}
回答by Krunal
A simpler way:
一个更简单的方法:
Detect IE:
检测IE:
function detectIE() {
var ua = window.navigator.userAgent,
msie = ua.indexOf('MSIE '),
trident = ua.indexOf('Trident/'),
edge = ua.indexOf('Edge/');
if (msie > 0) {return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);}
if (trident > 0) {var rv = ua.indexOf('rv:');return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);}
if (edge > 0) {return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);}
return false;
}
Differentiate XMLhttp and XDomain:
区分 XMLhttp 和 XDomain:
var url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%27pune%2Cmh%27)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithke"
if (window.XDomainRequest && detectIE()) {
var xdr = new XDomainRequest();
xdr.open("GET", url, false);
xdr.onload = function () {
var res = JSON.parse(xdr.responseText);
if (res == null || typeof (res) == 'undefined')
{
res = JSON.parse(data.firstChild.textContent);
}
publishData(res);
};
xdr.send();
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200 || xmlhttp.status == 304) {
publishData(JSON.parse(xmlhttp.responseText));
} else {
setTimeout(function(){ console.log("Request failed!") }, 0);
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function publishData(data){
console.log(data); //Response
}
Full Example can be found here
完整示例可以在这里找到

