最简单的方法来检索跨浏览器XmlHttpRequest [英] Easiest way to retrieve cross-browser XmlHttpRequest
问题描述
检索适用于所有浏览器的XmlHttpRequest对象的最简单和最安全的方法是什么?没有任何额外的库。是否有您经常使用的代码段?
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?
我知道网上有很多例子,但这正是我要求的原因:有太多不同的例子,我只想要一些简单的,被证明是有效的。
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.
jQuery and other libraries is NOT an option. Why does jquery leak memory so badly?
推荐答案
我有时使用这个片段从< a href =http://www.quirksmode.org/js/xmlhttp.html =nofollow noreferrer> quirksmode.org
I sometimes use this snippet from quirksmode.org
但)
function sendRequest(url,callback,postData) {
var req = createXMLHTTPObject();
if (!req) return;
var method = (postData) ? "POST" : "GET";
req.open(method,url,true);
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("Msxml2.XMLHTTP")},
function () {return new ActiveXObject("Msxml3.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;
}
这篇关于最简单的方法来检索跨浏览器XmlHttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!