我是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>
Run Code Online (Sandbox Code Playgroud)
无论如何,当我在我的本地服务器上运行它时,我试图在表中显示的数据都没有出现.我的.html文件和.xml文件在同一个文件夹中,所以我相信我有正确的文件路径.我可能只是在这里犯了一个菜鸟错误,但我不能为我的生活弄清楚为什么没有创建列出c_id和facebook_id值的表.我四处寻找答案,但却找不到任何答案.任何帮助将不胜感激.谢谢!
Jef*_*ney 14
您需要在发送请求之前添加onload事件侦听器xmlhttprequest.此外,您可能需要使用a解析XML DOMParser.无论如何,这应该适用于现代浏览器:
<!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>
Run Code Online (Sandbox Code Playgroud)
现在,只是值得一提的有关你正在做的事情:
xmlhttprequest对象有许多不同的参数,意味着各种各样的东西:readystate状态代码,作品.您可能会从中获益更多.
document.write应该永远不会被使用.事实上,任何HTML注入方式都应该非常谨慎地处理.您可以使用许多MVC-esque框架中常见的基于模板的解决方案,如果您愿意,可以使用我的 :)
| 归档时间: |
|
| 查看次数: |
47345 次 |
| 最近记录: |