检索适用于所有浏览器的XmlHttpRequest对象的最简单和最安全的方法是什么?没有任何额外的库。有没有经常使用的代码片段?检索跨浏览器的最简单方法XmlHttpRequest
P.S.我知道网络上有很多例子,但这正是我问的原因:有太多不同的例子,我只是想要一些简单并且已经证明可行的例子。
jQuery和其他库不是一个选项。 Why does jquery leak memory so badly?
检索适用于所有浏览器的XmlHttpRequest对象的最简单和最安全的方法是什么?没有任何额外的库。有没有经常使用的代码片段?检索跨浏览器的最简单方法XmlHttpRequest
P.S.我知道网络上有很多例子,但这正是我问的原因:有太多不同的例子,我只是想要一些简单并且已经证明可行的例子。
jQuery和其他库不是一个选项。 Why does jquery leak memory so badly?
虽然我会建议使用一个完整的音乐库,使使用更方便,使得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();
下面的代码片断是基于一个片段更先进的片段从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;
}
我们已经在使用jQuery,但它会泄漏内存,这对我们来说至关重要。感谢该片段,我会尝试一下。 – 2010-03-31 23:58:46
哪个浏览器使用Msxml3?我以前没有见过。 – 2010-04-01 00:18:21
任何没有Msxml6可用的系统(Microsoft.XMLHTTP将调用)。我知道至少Windows 2000 SP4有Msxml3可用:) – Wolph 2010-04-01 00:53:14
不是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
}
按照要求的问题,简单和行之有效的工作:
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;
}
根据IE开发中心的说法,我引用了“为了支持比IE7更早的IE版本,您可以使用:”return new ActiveXObject(“ MSXML2.XMLHTTP.3.0“) – andreszs 2014-08-15 23:37:08
@Andrew,是的,链接是在这里:https://msdn.microsoft.com/en-us/library/ms535874(v=vs.85).aspx#code-snippet-4。旧的浏览器真的很头疼,尽管现在对于个人项目来说,我很可能会简单地使用'new XMLHttpRequest();'。 – Pacerier 2015-11-26 04:58:09
更简单的方法:
检测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;
}
微分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
}
完整的例子可以发现here
我知道你说的 “不使用外部库”,但答案*仍然*“使用jQuery”。它压缩了25k。 – cletus 2010-03-31 23:47:30
使用jQuery是因为它简单易用 – 2010-03-31 23:47:32
另一个伟大的库是原型。但是,你能解释为什么你不想使用图书馆吗?他们可以让你的生活变得更轻松.. – 2010-03-31 23:49:40