gpt4 book ai didi

javascript - 带有 JSON 数据的动态 Javascript 表

转载 作者:行者123 更新时间:2023-12-03 08:13:47 26 4
gpt4 key购买 nike

我正在尝试使用从 PHP 脚本获取的 Javascript 和 JSON 数据创建和填充动态表。我遇到的问题是创建了第一行(标题),并且 JSON 对象中的键被放置在正确的位置,但我无法使用与这些键关联的值创建第二行(或者它不会显示)。这是我的 JS 代码:

var oReq = new XMLHttpRequest(); //New request object
oReq.onload = function() {
var Json = JSON.parse(this.responseText);
for (value in Json.prods[0]){
alert(value);
}
var newTable = document.createElement('table');

//Create first row
var tableRowFirst = document.createElement('tr');

for (key in Json.prods[0]) {
//create new heading
var keys = document.createElement('th');

// append Heading to table
tableRowFirst.appendChild(keys);

//set new heading text content to json information
keys.textContent = key;
};

//Create rows
var tableBody = document.createElement('tbody');
var tableRow = document.createElement('tr');
tableBody.appendChild(tableRow);

for (key in Json.prods[0]) {
//create new cell
var values = document.createElement('td');

// append cell to row
tableRow.appendChild(values);

//set new content text content to json information
values.textContent = Json.prods[0].key;
};

//Append table to DOM
document.body.appendChild(newTable);

//Append rows to new table
newTable.appendChild(tableRowFirst);
newTable.appendChild(tableBody);
};
oReq.open("get", "../php/getalltag.php", true);
oReq.send();

谁能帮帮我吗?

最佳答案

我猜您以错误的方式设置了 textContent,因为您试图获取名为 key 的属性,但 key 实际上是一个存储真实属性名称的局部变量。

 for (key in Json.prods[0]) {
...

//set new content text content to json information
values.textContent = Json.prods[0].key;
};

这应该没问题:

values.textContent = Json.prods[0][key];

关于javascript - 带有 JSON 数据的动态 Javascript 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34042286/

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