簡體   English   中英

XMLHttpRequest無法加載http:// localhost:8081 / sample.xml。 Access-Control-Allow-Origin不允許使用null。

[英]XMLHttpRequest cannot load http://localhost:8081/sample.xml. Origin null is not allowed by Access-Control-Allow-Origin.

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(url)
{
var xmlhttp;
var txt,x,xx,i;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
txt="<table border='1'><tr><th>Author</th><th>Title</th></tr>";
x=xmlhttp.responseXML.documentElement.getElementsByTagName("book");
for (i=0;i<x.length;i++)
  {
  txt=txt + "<tr>";     
  xx=x[i].getElementsByTagName("author");
    {
    try
      {
      txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
      }
    catch (er)
      {
      txt=txt + "<td> </td>";
      }
    }
    xx=x[i].getElementsByTagName("title");
    {
    try
      {
      txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
      }
    catch (er)
      {
      txt=txt + "<td> </td>";
      }
    }
  txt=txt + "</tr>";
  }
txt=txt + "</table>";
document.getElementById('txtCDInfo').innerHTML=txt;
 }
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="txtCDInfo">
<button onclick="loadXMLDoc('http://localhost:8081/sample.xml')">GetDetails</button>
</div>
</body>
</html>

我已經寫了上面的代碼行來顯示xml文件數據。它被部署在iis服務器上。每當我想訪問xml文件時,它顯示上面的錯誤。我在做錯了什么錯。我必須在url位置寫獲取xml文件。如果我只寫像sample.xml這樣的文件名。它顯示錯誤,如拒絕訪問。

這是因為同源政策 你不能使用ajax來調用外部網站。 如果你真的想使用,你必須使用JSONP 或者您可以使用服務器端代理。 意味着,在服務器端調用外部站點並對該Web服務執行ajax調用。 有關更多詳細信息,請參閱我對以下問題的回答, $ .ajax調用在IE8中工作正常,並且在Firefox和Chrome瀏覽器中不起作用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM