【问题标题】:JSON data to a table in HTMLJSON 数据到 HTML 中的表格
【发布时间】:2018-11-01 13:33:11
【问题描述】:

如何获取 JSON 数据到 HTML 表格中

我正在取回 JSON 数据并尝试附加到如下表中,但它不起作用

  <table>
<thead>
        <tr>SerialNo</tr>
        <tr>Name</tr>
    </thead>
<tbody id="dynamicTbody"></tbody>
</table>


$.getJSON(url, function (json) {

    ADD JSON DATA TO THE TABLE 
    for (var i = 0; i < json.records.length; i++) {

 $('#dynamicTbody').append('<tr><td>'+json.records[i].SerNo.SerialNo+'</td><td>'+json.records[i].name.Name+'</td></tr>')
}}

因为我的问题不够清楚,所以编辑了这个

【问题讨论】:

  • JSON 文本是什么样的?您应该能够在没有 $.getJSONvar json = {...} 的情况下发布可运行的片段。
  • /* Headings for the table 是语法错误,/ FINALLY... 也是如此。单行 cmets 以 // 开头,多行 cmets 必须关闭:/* ... */for 块没有关闭,HTML 中没有 JSONdata 元素。

标签: javascript json html-table


【解决方案1】:

const records = [
  {SerialNo: 1, name: 'User 1'},
  {SerialNo: 2, name: 'User 2'},
  {SerialNo: 3, name: 'User 3'},
  {SerialNo: 4, name: 'User 4'},
  {SerialNo: 5, name: 'User 5'},
];

const table = document.createElement('TABLE');

records.forEach(record => {
  let row = table.insertRow();
  row.insertCell().appendChild(document.createTextNode(record.SerialNo));
  row.insertCell().appendChild(document.createTextNode(record.name));
});

document.getElementById('JSONdata').appendChild(table);
&lt;div id="JSONdata"&gt;&lt;/div&gt;

【讨论】:

  • 您好,谢谢您-我目前正在执行您的建议-
  • 但这不是我想要的......对不起,问题不清楚......我已经修改了问题
  • 一个好的答案应该解释为什么 OP 有问题以及您的代码如何修复它。这本质上只是对 OP 代码的重构。目前尚不清楚为什么 OP 的代码不起作用,因此目前还不能提供一个好的答案。
猜你喜欢
  • 2013-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 2015-06-25
  • 2021-10-21
  • 1970-01-01
相关资源
最近更新 更多