我正在使用 $.ajax
进行跨域请求。它适用于 Firefox 和 Chrome,但不会在 IE 7 或 8 上发出调用。任何人都可以告诉我以下内容有什么问题吗?
- 我使用过 JSON 和 JSONP(由于一些自定义限制,我不再使用它们)。
- 我已经在我的网站上使用了
Allow-access-control-origin
header 。 (没有这些,Chrome 和 Firefox 无法发出成功的请求。) - 我已经试过了https://developer.mozilla.org/en/http_access_control
代码:
$.ajax({
type: 'GET',
url: "http://anotherdomain.com/Service/GetControl?id=" + zoneID,
cache: false,
contentType: "application/x-www-form-urlencoded",
async: false,
beforeSend: function (request) {
//alert('before send');
//request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
//request.setRequestHeader("X-PINGOTHER", "pingpong");
} ,
success: function (data, status) {
//alert("Data returned :" + data);
//alert("Status :" + status);
if (status == "success" && data != "")
$("#" + div.id).append(data);
else
$("#" + div.id).attr("style", "display:none;");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
});
我尝试了多个网站上的各种提示,但还没有成功。
最佳答案
对于 IE8 和 IE9,您需要使用 XDomainRequest (XDR)。如果您看下面,您会发现它的格式类似于 $.ajax。就我的研究而言,我无法让这个跨域在 IE6 和 7 中工作(仍在为此寻找解决方法)。 XDR 首次出现在 IE8 中(它也在 IE9 中)。所以基本上首先,我测试 6/7 并且不执行 AJAX。
IE10+ 可以像其他所有浏览器一样正常跨域(恭喜微软……唉)
之后 else if 在窗口中测试 'XDomainRequest(显然比浏览器嗅探更好)并以这种方式执行 JSON AJAX 请求,否则 ELSE 通常使用 $.ajax 执行它。
希望对您有所帮助!!我花了很长时间才弄清楚这一切
Information on the XDomainRequest object
// call with your url (with parameters)
// 2nd param is your callback function (which will be passed the json DATA back)
crossDomainAjax('http://www.somecrossdomaincall.com/?blah=123', function (data) {
// success logic
});
function crossDomainAjax (url, successCallback) {
// IE8 & 9 only Cross domain JSON GET request
if ('XDomainRequest' in window && window.XDomainRequest !== null) {
var xdr = new XDomainRequest(); // Use Microsoft XDR
xdr.open('get', url);
xdr.onload = function () {
var dom = new ActiveXObject('Microsoft.XMLDOM'),
JSON = $.parseJSON(xdr.responseText);
dom.async = false;
if (JSON == null || typeof (JSON) == 'undefined') {
JSON = $.parseJSON(data.firstChild.textContent);
}
successCallback(JSON); // internal function
};
xdr.onerror = function() {
_result = false;
};
xdr.send();
}
// IE7 and lower can't do cross domain
else if (navigator.userAgent.indexOf('MSIE') != -1 &&
parseInt(navigator.userAgent.match(/MSIE ([\d.]+)/)[1], 10) < 8) {
return false;
}
// Do normal jQuery AJAX for everything else
else {
$.ajax({
url: url,
cache: false,
dataType: 'json',
type: 'GET',
async: false, // must be set to false
success: function (data, success) {
successCallback(data);
}
});
}
}
关于Jquery $.ajax 在跨域调用时在 IE 中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3362474/