简体   繁体   中英

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>

I have written above lines of code for showing xml file data.And it was deployed in iis server.Whenever i wanted to access xml file,It is showing above error.Where am i doing wrong mistake.What i have to write in url position for getting xml file.If i write only file name like sample.xml.It showing error like Access denied.

this is because of the Same origin policy . you cannot use ajax to call external sites. if you really want to use, you have to use JSONP . Or you can use serverside proxy for this. means, call external site in the server side and do ajax call to the that webservice. For more details see my answer on following question, $.ajax call working fine in IE8 and Doesn't work in firefox and chrome browsers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM