我是 Stack OverFlow 和一般编码的新手。我正在尝试获取一个 XML 文件并使用 JavaScript 在浏览器中呈现它。我查看了一些有关如何执行此操作的示例代码,并提出了以下代码:
<!DOCTYPE html>
<html>
<body>
<script>
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","social.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.write("<table border='1'>");
var x=xmlDoc.getElementsByTagName("CD");
for (i=0;i<x.length;i++)
{
document.write("<tr><td>");
document.write(x[i].getElementsByTagName("c_id")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("facebook_id")[0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
document.write("</table>");
</script>
</body>
</html>
无论如何,当我在我的本地服务器上运行它时,我试图在表格中显示的数据都没有出现。我的 .html 文件和 .xml 文件在同一个文件夹中,所以我相信我有正确的文件路径。我可能只是在这里犯了一个新手错误,但我终其一生都无法弄清楚为什么没有创建列出 c_id 和 facebook_id 值的表。我环顾四周寻找答案,但一直找不到任何答案。任何帮助将不胜感激。谢谢!
最佳答案
发送请求前需要给xmlhttprequest
添加一个onload
事件监听器。此外,您可能需要使用 DOMParser
解析 XML。无论如何,这应该适用于现代浏览器:
<!DOCTYPE html>
<html>
<body>
<script>
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onload = function() {
var xmlDoc = new DOMParser().parseFromString(xmlhttp.responseText,'text/xml');
console.log(xmlDoc);
document.write("<table border='1'>");
var x=xmlDoc.getElementsByTagName("CD");
for (i=0;i<x.length;i++)
{
document.write("<tr><td>");
document.write(x[i].getElementsByTagName("c_id")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("facebook_id")[0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
document.write("</table>");
}
xmlhttp.open("GET","social.xml",false);
xmlhttp.send();
</script>
</body>
</html>
现在,关于您正在做的事情,有几件事值得一提:
xmlhttprequest
对象有许多不同的参数,这些参数表示各种事物:readystate
、状态代码、工作。您可能会从中受益更多。document.write
永远不应该被使用。事实上,应该非常小心地处理任何 HTML 注入(inject)方式。您可以使用许多 MVC 式框架中常见的基于模板的解决方案,或 mine如果你愿意:)
关于javascript - 使用 JavaScript 解析 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13204165/