我是javascript的新手。我想从url读取xml并想在html上解析它。我有像这样的html和javascript代码:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function loadXMLDoc(filename)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // code for IE5 and IE6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}
xmlDoc=loadXMLDoc("http://www.w3schools.com/dom/books.xml");
x=xmlDoc.getElementsByTagName("title")[0];
y=x.childNodes[0];
document.write(y.nodeValue);
</script>
</body>
</html>
&#13;
有什么问题?感谢
答案 0 :(得分:-1)
这是执行此任务的标准方法:
由于人们继续沿着尝试使用跨域而不是JSONP的路径... 它将无法工作!
下面的代码是一个可行的示例,因为您的服务器可以从其他网络位置获取更受控制的内容。另一方面,您的浏览器只能接收JSONP或PLAIN TEXT ...大多数谷歌的结果也应该解释一下..
您唯一的选择
使用某种形式的 PROXY 来获取您尝试访问的内容,因此您只有三种选择。
JAVASCRIPT:
function loadXMLDoc(sURL) {
$.post( "myproxy.php", { requrl: sURL }).done(function( data ) {
alert(data);
console.log(data);
document.write(data);
});
}
PHP:myproxy.php
<?php
header('Content-Type: application/xml; charset=utf-8');
$file = file_get_contents($_POST['requrl']);
echo $file;
?>
请注意,您打算将其与其他类型的内容一起使用,然后您需要更改/删除标题行。
您的浏览器允许您从其他网站使用AJAX XML
如果是这种情况,那么您需要更换或更新您的网络浏览器..
上述解决方案并非复杂
这是几乎可以复制和粘贴的代码,JS函数将以三种最常见的方式返回结果/数据/内容......
PHP脚本也是一个复制和粘贴..所以如果你安装了PHP。
您需要做的就是在与html文档相同的位置创建一个新文本文件,并将其命名为“myproxy.php”,此示例将起作用。
答案 1 :(得分:-2)
这是一个合适的XmlHttpRequest,带有一个回调函数来处理你的XML:
<!DOCTYPE html>
<html>
<head></head>
<body>
<script type="text/javascript">
function loadXMLDoc(url){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callbackFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function callbackFunction(response){
if (window.DOMParser){ // Non IE
var parser = new DOMParser();
var xml_doc = parser.parseFromString(response,"text/xml");
}else{ // Internet Explorer
var xml_doc = new ActiveXObject("Microsoft.XMLDOM");
xml_doc.async = false;
xml_doc.loadXML(response);
}
// Do something with your 'xml_doc' object variable here
console.log(xml_doc) // Debugging only.. to see the XML in the browser console for your own reference
var x = xml_doc.getElementsByTagName("title")[0]
var y = x.childNodes[0];
document.write(y.nodeValue);
}
// Call the function to begin code execution
loadXMLDoc('http://www.w3schools.com/dom/books.xml')
</script>
</body>
</html>
这是正常工作的代码,因此您可以删除所拥有的内容并将其直接替换掉。祝你好运!
如果您计划在自己的服务器上托管文件以通过XHR访问,我提供的代码就是为此而设。如果w3schools.com在您请求的XML文件上有一个“Access-Control-Allow-Origin:*”标题,它也可以。但他们没有。因此,您需要将XML文件放在浏览器安全性允许您访问它的位置(与您的网页相同的域名来源)。否则,您的浏览器将继续阻止资源在控制台中出现“跨源请求阻止”错误。