gpt4 book ai didi

javascript - json数据未显示在js生成的表中

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

我在 js 中有一个来自 php 的变量,例如:

var myData = <?php echo json_encode($json_array) ?>; 

我正在尝试将此 obj 的键和值传递到由 javascript 生成的表。控制台中的 myData 格式粘贴在下面。当我将它传递到表时,我收到一条错误消息,说它无法读取我的数据。我知道我可以将数据作为对象传递,但不知怎的,这是不同的,因为我从 php 引入并且没有像常规 json 文件那样读取它。我得到的错误是: Uncaught TypeError: Cannot read property 'insertRow' of null在生成表?

myData 在控制台中输出的内容:

0:
Carat: "0.70"
Clarity: "VVS2"
Color: "D"
Cut: "Very Good"
Polish: "Fair"
Price: "2806"
Product ID: "17"
Product Name: "0.7 Carat Cushion Diamond"
Report: "IGI"
Shape: "Cushion"
Symmetry: "Ideal"
purl: "http://klaussongs.com/product/0-7-carat-cushion-diamond/"
__proto__: Object
1: {Product ID: "19", Product Name: "0.9 Carat Round Diamond", Carat: "0.90", Clarity: "VS2", Shape: "Round", …}
2: {Product ID: "21", Product Name: "1 Carat Radiant Diamond", Carat: "1.00", Clarity: "SI1", Shape: "Radiant", …}
3: {Product ID: "23", Product Name: "1.15 Carat Princess Diamond", Carat: "1.15", Clarity: "IF", Shape: "Princess", …}

从 myData 生成表的函数:

function generateTableHead(table, data) {
let thead = table.createTHead();
let row = thead.insertRow();
for (let key of data) {
let th = document.createElement("th");
let text = document.createTextNode(key);
th.appendChild(text);
row.appendChild(th);
}
}

function generateTable(table, data) {
for (let element of data) {
let row = table.insertRow();
for (key in element) {
let cell = row.insertCell();
let text = document.createTextNode(element[key]);
cell.appendChild(text);
}
}
}


let table = document.querySelector("table");


let data = Object.keys(myData);


// generate cells from values
generateTable(table, myData);


// create heading from keys
generateTableHead(table, data);

最佳答案

看起来这个 let table = document.querySelector("table"); 返回 null。您确定运行此查询时已创建表元素吗?您能确认这返回 null 吗?

关于javascript - json数据未显示在js生成的表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57998873/

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