[英]XDomainRequest (CORS) for XML causing “Access is denied” error in IE8 / IE9
如果這似乎是重復的道歉,但我無法看到任何類似問題的明確答案。
當嘗試對某些XML執行CORS請求時,我不斷從IE8獲得“訪問被拒絕”JS錯誤。
我的代碼改編自這個例子:
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
// Helper method to parse the title tag from the response.
function getTitle(text) {
return text.match('<title>(.*)?</title>')[1];
}
// Make the actual CORS request.
function makeCorsRequest() {
// All HTML5 Rocks properties support CORS.
var url = 'http://updates.html5rocks.com';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
var title = getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
來自http://www.html5rocks.com/en/tutorials/cors/
這應該在使用XDomainRequest的IE8中工作,當我加載示例頁面並單擊html5rocks頁面上的“Run sample”時,它可以在IE8中運行。 但是,只要我將代碼復制到我自己的頁面並運行,我就會在XDomainRequest內的xhr.open()行上出現“訪問被拒絕”錯誤。
這個讓我感到困惑 - 服務器肯定是正確設置的,所以它與前端有關。 提前感謝任何可以提供幫助的人!
好吧,問題歸結為IE8和9中的奇怪問題,這些問題通過本文的一些建議得到解決: http : //cypressnorth.com/programming/internet-explorer-aborting-ajax-requests-fixed/ (主要是設置一些空白)處理程序函數並將.send()包裝在0超時中。
這是我的最終代碼,適用於ie8 / 9/10/11和FF / Chrome:
function doRequest(url) {
// Create the XHR object.
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open('get', url, true);
}else if(typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open('get', url);
}else{
// CORS not supported.
xhr = null;
};
if (!xhr) {
return;
};
// Response handlers.
xhr.onload = function() {
//do what you want with the response. Remember to use xhr.responseText for ie8 compatibility, because it doesn't have .responseXML
if(xhr.responseXML) {
xml = this.responseXML;
}else if(xhr.responseText){
xml = new ActiveXObject('Microsoft.XMLDOM');
xml.loadXML(xhr.responseText);
};
};
xhr.onerror = function() {
//do what you want on error
};
//these blank handlers need to be set to fix ie9 http://cypressnorth.com/programming/internet-explorer-aborting-ajax-requests-fixed/
xhr.onprogress = function () { };
xhr.ontimeout = function () { };
//do it, wrapped in timeout to fix ie9
setTimeout(function () {
xhr.send();
}, 0);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.