繁体   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