gpt4 book ai didi

Javascript JSON 数据到 HTML 表

转载 作者:行者123 更新时间:2023-12-02 19:02:47 25 4
gpt4 key购买 nike

我有一些代码,现在将其粘贴在下面。该代码的作用是读取 XML 文件的内容并将其放入 JSON 中。然后将 JSON 中的数据放入 HTML 表中。除了一件事之外,一切正常。创建表格后,第一行(在列标题之后)在每个单元格中始终显示为“未定义”。我已经查看了这段代码,但找不到任何会导致它的原因,但我不是专家,我确​​信一双新的眼睛会有所帮助,所以有什么想法吗?

<html>
<head>
<h1><u>USA State Information</u></h1>
</head>
<body>
<p><b>Please select an area of the USA in the dropdown list below.</b></p>
<p><select name="area" onchange="findXML(this.value)">

<?php
//set directory and open it
$xmldir = 'XML';
$dir = opendir($xmldir);

//create array and read through files in directory
$xmlfiles = array();
while ($file = readdir($dir))
{
//if the first char is not '.' then add to array
if (substr($file,-1,1) !== ".")
{
$xmlfiles[] = $file;
}
else
{
//do nothing
}
}

echo '<option value="select">Select</option>';

foreach($xmlfiles as $area){
echo '<option value="'.$area.'">'.$area.'</option>';
}
echo '</select>';

//close directory
closedir($dir);
?>
</p>
<p>
<div id=tbl>
</div>
<table id="elems" border="1" cellspacing="1" cellpadding="5">
<tr>
<td><b>Name</></td>
<td><b>Number</></td>
<td><b>Joined</></td>
<td><b>Population</></td>
</tr>
</table>
<script>
function findXML($area) {
$area = "XML/" + $area;
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",$area,true);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
//find number of elements in the XML file
$length = xmlDoc.getElementsByTagName("name").length;

var JSONObject = [{}];
for (i=0; i!=$length; i++){
//do something

JSONObject.push(
{ "name":(xmlDoc.getElementsByTagName("name")[i].childNodes[0].nodeValue),
"number":(xmlDoc.getElementsByTagName("number")[i].childNodes[0].nodeValue),
"joined":(xmlDoc.getElementsByTagName("joined")[i].childNodes[0].nodeValue),
"population":(xmlDoc.getElementsByTagName("population")[i].childNodes[0].nodeValue) }
);
}

r=1;
i=0;
for (i=0; i!=($length); i++){

var tblr = document.getElementById("elems").insertRow(r);
var cell1= tblr.insertCell(0);
var cell2= tblr.insertCell(1);
var cell3= tblr.insertCell(2);
var cell4= tblr.insertCell(3);
cell1.innerHTML = JSONObject[i].name;
cell2.innerHTML = JSONObject[i].number;
cell3.innerHTML = JSONObject[i].joined;
cell4.innerHTML = JSONObject[i].population;
r++;
}

}
</script>
</p>

</table>
</body>
</html>

最佳答案

我想我发现了问题:

var JSONObject = [{}];

应该是

var JSONObject = [];

解决此问题的原因是您从第一个索引开始迭代 JSONObject 数组。这很好,但是初始化数组的方式给了第一个索引一个空对象。当你去获取属性namenumber等时,空对象不会有它们,它们将以未定义的形式返回。

关于Javascript JSON 数据到 HTML 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14636252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com