XMLHttpRequest无法加载http://localhost:8081/sample.xml.Access-Co

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

本文关键字:8081 sample xml Access-Co localhost 加载 http XMLHttpRequest      更新时间:2023-09-26
<!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浏览器中不起作用