我正在读取 XML 文件并将其显示在网页上。 我正在使用一个 JS 脚本来读取 XML 文件并在表中显示信息。 但是,当页面加载时,单元格内的信息显示“UNDEFINED”。 该表格应显示该人的姓名和听证室信息。
我已经尝试了这篇堆栈溢出文章中的最佳解决方案:如何使 JavaScript 在页面加载后执行?
我检查了拼写错误和 XML 文件的结构,并阅读了其他几篇有关堆栈溢出的文章,但没有成功。
我的JS脚本:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title></title>
<script>
var client;
if (window.XMLHttpRequest)
{
client = new XMLHttpRequest();
}
else
{
client = new ActiveXObject("Microsoft.XMLHTTP");
}
client.open('GET', 'TestData.xml', true);
client.onload = function() // Function to run when the file loads
{
// get the response XML
var xmlDoc = client.responseXML;
// get the list
var hearings = xmlDoc.getElementsByTagName("hr");
// get the container where you want to embed the table
var container = document.getElementById("container");
// Create a table and put the data inside it
var tableString = "<table border = '1'>";
for (i = 0; i < hearings.length; i++)
{
tableString += "<tr><td>";
tableString += hearings[i].getElementsByTagName("name")[0].childNodes[0].nodValue;
tableString += "<tr><td>";
tableString += hearings[i].getElementsByTagName("hearing_room")[0].childNodes[0].nodValue;
tableString += "<tr><td>";
}
tableString +="</table>";
// append the table to the container
container.innerHTML = tableString;
}
client.send();
</script>
</head>
<body>
<h1></h1>
<div id="container"></div>
</body>
</html>
我的 XML 文档:
<?xml version="1.0" ?>
<hearing name="hearing_schedule">
<hr>
<name>Michelle</name>
<hearing_room>M028</hearing_room>
</hr>
<hr>
<name>Matthews</name>
<hearing_room>M028</hearing_room>
</hr>
<hr>
<name>Anita</name>
<hearing_room>M028</hearing_room>
</hr>
</hearing>
尝试不同的选择器,因为您只期望每个元素中的一个
所以,你应该能够使用querySelector()
var tableString = "<table border = '1'>";
for (i = 0; i < hearings.length; i++) {
tableString += "<tr><td>";
tableString += hearings[i].querySelector("#name").innerText;
tableString += "<tr><td>";
tableString += hearings[i].querySelector("hearing_room").innerText;
tableString += "<tr><td>";
}
您需要避免访问未定义对象上的属性并定义后备。
const foo = undefined;
// operator "?." avoids accessing undefined properties
console.log(foo?.bar);
// use the "||" operator
console.log(foo?.bar || 'fallback');
浏览器现在支持
fetch()
API。这减少了所需的源,并且可以与 async/await 一起使用。
fetchAndDisplay(
document.querySelector("#container tbody")
);
// define the function as async - so it can await results of
// other async calls
async function fetchAndDisplay(container) {
// wait for the fetched data
const xml = await fetchXML();
// clear all nodes inside the target container
container.textContent = '';
// fetch all hr elements as an array
const hearings = [...xml.querySelectorAll('hr')];
// append mapped hearings
container.append(
...hearings.map(
// map hearing into table row
function (hr) {
// create row
const row = document.createElement('tr');
// create + append cells, use querySelector to fetch content
row.append(
createTableCell(hr.querySelector('name')?.textContent || ''),
createTableCell(hr.querySelector('hearing_room')?.textContent || ''),
);
return row;
}
));
}
function createTableCell(textContent) {
const cell = document.createElement('td');
cell.textContent = textContent;
return cell;
}
async function fetchXML() {
// fetch + parse XML, use string for example
return (new DOMParser).parseFromString(
// await fetch('http://...')
`<?xml version="1.0" ?>
<hearing name="hearing_schedule">
<hr>
<name>Michelle</name>
<hearing_room>M028</hearing_room>
</hr>
<hr>
<name>Matthews</name>
<hearing_room>M028</hearing_room>
</hr>
<hr>
<name>Anita</name>
<hearing_room>M028</hearing_room>
</hr>
</hearing>`,
'application/xml'
);
}
<table id="container">
<tr>
<th>Name</th>
<th>Room</th>
<tr>
<tbody>
</tbody>
</table>