gpt4 book ai didi

javascript - 如何使用 JS 和 JQuery 在表格中显示 JSON 数据(没有正确的标签)?

转载 作者:行者123 更新时间:2023-12-01 00:11:07 24 4
gpt4 key购买 nike

所以我通过Ajax调用将JSON数据解析到前端。 JSON 数据的格式如下所示:

 { 
"num_meetings":{
"EOF/TRiO":{
"4 Meetings":1,
"11 Meetings":1
},
"Learning Center":{
"1 Meetings":8,
"2 Meetings":10,
"3 Meetings":4,
"4 Meetings":9,
"5 Meetings":2,
"6 Meetings":1,
"7 Meetings":2,
"8 Meetings":1,
"13 Meetings":1
},
"Student Success Coach Office":{
"3 Meetings":2,
"4 Meetings":1
}
}
}

如何在前端的表格中显示它?

我试图用这个片段来解决这个问题:

  var tabular = resp.msg.num_meetings;

var html = "";
html += "<table class='table small table-responsible-sm table hover table-sm table-stripped'>";
html += `<tr><th>Location</th><th>Attended</th></tr>`;

tabular.forEach(function(elem,index) {
html += `<tr>`;
html += `<td><b>${elem.???}</b></td>`;
html += `</tr>`;
});
html += "</table>";
return html;

我不确定如何访问 num_meetings 内的元素。

表格看起来像这样:

----------------------------------
Location | Meetings | Attendance
----------------------------------
EOF/TRio | 4 Meetings | 1
----------------------------------
EOF/TRio | 11 Meetings | 1
----------------------------------
Learning Center ....

最佳答案

您需要为“num_meetings”内每个对象的每个值创建一行(tr)。

因此,要以简单的方式做到这一点,您需要两个循环。我循环遍历 num_meetings 键,然后获取其值并循环遍历其中的所有值。有点令人困惑,但是看看代码,我想你就会明白。

var resp = {
"msg": {
"num_meetings": {
"EOF/TRiO": {
"4 Meetings": 1,
"11 Meetings": 1
},
"Learning Center": {
"1 Meetings": 8,
"2 Meetings": 10,
"3 Meetings": 4,
"4 Meetings": 9,
"5 Meetings": 2,
"6 Meetings": 1,
"7 Meetings": 2,
"8 Meetings": 1,
"13 Meetings": 1
},
"Student Success Coach Office": {
"3 Meetings": 2,
"4 Meetings": 1
}
}
}
}

//-- let's work with the data now --\\
var tabular = resp.msg.num_meetings;
var html = "";

html += "<table class='table small table-responsible-sm table hover table-sm table stripped'>";
html += "<tr><th>Location</th><th>Meetings</th><th>Attendance</th></tr>";

for (let key in tabular) {
let obj = tabular[key]

for (let innerKey in obj) {
html += `<tr>`;
html += `<td>${key}</td>`;
html += `<td>${innerKey}</td>`;
html += `<td>${obj[innerKey]}</td>`;
html += `</tr>`;
}

};

document.body.innerHTML = html
td {
border: 1px solid
}

.forEach 在这里不起作用,因为 resp.msg.num_meetings 不是数组而是对象,这就是我使用 for 的原因。 .in

关于javascript - 如何使用 JS 和 JQuery 在表格中显示 JSON 数据(没有正确的标签)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60061482/

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