【发布时间】:2022-02-11 08:10:51
【问题描述】:
我在多个浏览器上尝试了来自 tutorialspoint 网站的示例代码。但是xml数据没有被解析。这两个文件都在我的本地系统上,并且 address.xml 文件位于文件夹“xml”中。
如何从本地系统上的 xml 文件中解析 javascript 中的数据?
这是我来自 tutorialspoint 网站的 HTML 文件 sample.html:
<!DOCTYPE html>
<html>
<body>
<h1>TutorialsPoint DOM example </h1>
<div>
<b>Name:</b> <span id="name"></span><br>
<b>Company:</b> <span id="company"></span><br>
<b>Phone:</b> <span id="phone"></span>
</div>
<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","/xml/address.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.getElementById("name").innerHTML=
xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
document.getElementById("company").innerHTML=
xmlDoc.getElementsByTagName("company")[0].childNodes[0].nodeValue;
document.getElementById("phone").innerHTML=
xmlDoc.getElementsByTagName("phone")[0].childNodes[0].nodeValue;
</script>
</body>
</html>
这是xml数据文件地址.xml:
<?xml version="1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>
更新:问题在于在本地系统上获得 http 响应。安装XAMPP后就解决了。
【问题讨论】:
-
您使用的是哪个浏览器?您在哪里阅读 addess.xml?我只看到对 sample.htm 的请求
-
您是否在浏览器开发者工具控制台中收到任何有用的错误消息?您能否使用浏览器开发者工具网络工具验证 XML 确实被正确发送了
-
请求是通过 http/https 发出的吗?
-
我已经在 chrome、firefox、opera 等多种浏览器上尝试过。这两个文件都在我的本地系统上的文件夹“xml”中。
-
不要做 "/xml/address.xml" ... 使用 "xml/address.xml" ... 但如果你是 not 使用 http 或 https(即您已使用 file:/// 加载文件)
标签: javascript html xml dom