我在許多瀏覽器上從tutorialspoint網站嘗試了這個示例代碼。但是XML數據沒有被解析。這兩個文件都在本地系統上,而address.xml文件位於「xml」文件夾中。無法使用本地系統上的javascript HTML DOM解析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數據文件address.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 – rplantiko
的請求是否在瀏覽器開發人員工具控制檯中收到任何有用的錯誤消息?您可以使用瀏覽器開發工具網絡工具驗證XML是否確實正確發送了 –
是通過http/https發出的請求嗎? –