我正在嘗試閱讀互聯網上的xml文件。它適用於IE,但不適用於Firefox/Chrome瀏覽器。 它在Firefox上給出下面的錯誤;從互聯網上閱讀xml文件 - 火狐瀏覽器上的Cross Origin Request Error錯誤
跨源請求被阻止:同源策略不允許讀取遠程資源http://xxxxx.com/YYYY.xml。這可以通過將資源移動到相同的域或啓用CORS來解決。
這是我的代碼;
<html>
<head>
<script>
function loadXMLDoc(filename)
{
if (window.ActiveXObject)
{
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
else
{
xhttp = new XMLHttpRequest();
}
xhttp.open("GET", filename, false);
try {xhttp.responseType = "msxml-document"} catch(err) {} // Helping IE11
xhttp.send("");
return xhttp.responseXML;
}
function displayResult()
{
xml = loadXMLDoc("http://xxxxx.com/YYYY.xml");
...........
.........
}
</script>
</head>
<body onload="displayResult()">
<div id="example" />
</body>
</html>
它返回就行了 xhttp.responseXML空;在loadXMLDoc函數中使用 。
得到這個錯誤後,我搜索了錯誤,並嘗試下面的代碼,使CORS請求。但它現在也可以工作。
// 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://xxxxx.com/YYYY.xml';
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();
}
在makeCorsRequest()函數,之後createCORSRequest()函數,是xhr.responseText 「」 和xhr.ResponseXML是null.In響應處理器,它給xhr.onerror。
你能幫我解決這個錯誤嗎? 謝謝。
UPDATE:
我想測試我的網頁在我的電腦(本地主機)。在IIS在我的電腦,我能與web.config中的CORS下面
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
在您必須啓用對CORS火狐
你在服務器上啓用了CORS嗎?它發送了什麼響應頭文件?開發人員工具的Net標籤顯示了什麼?它是否會提供您期望的HTTP請求?或者它做出OPTIONS預檢請求然後放棄? – Quentin
我想在我的電腦(本地主機)中測試我的頁面。在我的計算機上的IIS中,我使用了web.config啓用了CORS,在下面的頁面中對此進行了說明 –