我覺得我要把我的頭髮拉出來。我試圖從XML文件中獲取一些數據,並將其放入使用JavaScript的表格中。我查看了大約一百萬個示例,但由於某種原因,我無法實現它。我一直在使用DreamWeaver,Notepad ++和Brackets。 這是我的HTML文件。用JavaScript獲取XML數據
<head>
//<meta http-equiv="Content-Type" content="text/html; charset-UTF-8"/>
<script language="javascript" type="text/javascript" src="script2.js"></script>
<title>Computer Science Faculty Information</title>
<h1>Computer Science Faculty Information</h1>
<button onclick="readXML()">Read XML File</button>
<table id="first" border="1">
<tr>
<th>Name</th>
</tr>
</table>
我的XML文件
<?xml version="1.0?>
<department>
<employee>
<name>Ajay Katangur, Ph.D.</name>
<title>Program Coordinator</title>`
<office>CI 340</office>
<phone>361-825-2478</phone>
<email>[email protected]</email>
</employee>
</department>
和我的JS文件
function readXML() {
"use strict";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
myFunction(xmlhttp);
}
};
xmlhttp.open("GET", "xml.xml", true);
xmlhttp.send();
}
function myFunction(xml) {
"use strict";
var x, i, xmlDoc, table;
xmlDoc = xml.responseXML;
table = "<tr><th>Name</th><th>Title</th><th>Office</th><th>Phone</th><th>Email</th><tr>";
x = xmlDoc.getElementsByTagName("employee");
for(i = 0; i < x.length; i++) {
table += "<tr><td>" + x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("office")[0].childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("phone")[0].childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("email")[0].childNodes[0].nodeValue + "</td></tr>";
}
document.getElementById("first").innerHTML = table;
}
我應該提到的是,js代碼的很大一部分是在這裏從W3Schools的。請有人告訴我我做錯了什麼。提前致謝。
是什麼或不工作或沒有提到如果有錯誤,在瀏覽器開發工具控制檯拋出。 – charlietfl
好,所以重點在於當單擊按鈕時,應該調用js,並且它應該使用xml文件中的數據填充表。當我點擊按鈕時,沒有任何反應。 – jynx678
*「什麼都沒有發生」* ...有些事情......事件回調觸發器?您是否在網絡標籤中打開了瀏覽器開發工具並檢查了請求?控制檯中的任何錯誤?至少需要做一些基本的故障排除 – charlietfl