我只是想获取 xml 数据并使用 jscript 在 html 页面中显示它。根据this tutorial我写了一个示例代码
<script>
xmlDoc=loadXMLDoc("http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml");
x=xmlDoc.getElementsByTagName('city');
for(i=0;i<x.length;i++)
{
att=x.item(i).attributes.getNamedItem("name");
document.write(att.value + "<br>");
}
</script>
<script >
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}
</script>
我在 html 页面中的输出应该是“伦敦”。但它什么也没显示。或者请告诉我我的错误。
最佳答案
我认为您遇到了臭名昭著的 "same-origin policy" problem
总而言之,在 AJAX 中,您无法从远程服务器、应用程序或网站加载 XML 内容(这意味着 XML 数据不能源自您自己的域之外的任何域。
解决此问题的方法有很多,例如使用 server-side proxy ,而不是 XML 使用 JSONp或使用 CORS打破您的客户端应用程序在运行该代码时所在的沙箱(如果您的用户浏览器和您请求的服务器堆栈都支持它)。
关于javascript - xml 数据未显示在 html 页面中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20980380/