【发布时间】:2015-09-29 08:39:12
【问题描述】:
我尝试动态构建 HTML 表格是徒劳的。
代码有效,但它并不能完全输出我需要的东西。
我的 JSON 输出中只有 2 个属性:location 和 completed_on
而不是得到这个:
+-------------------+---------------------+
| Location | Completed on |
+-------------------+---------------------+
| 10 Duskwood Dr. | 2015-07-06 14:10:42 |
| 2 Booty Bay Blvd. | 2015-07-09 13:44:38 |
+-------------------+---------------------+
代码显示了这个(没有可见的标题):
[
{
"
l
o
c
a
...
]
... prints the whole JSON character by character inside many <td> tags...
这是我必须使用的典型 JSON 数据的示例:
[{"location":"10 Duskwood Dr.","completed_on":"2015-07-06 14:10:42"},
{"location":"2 Booty Bay Blvd.","completed_on":"2015-07-09 13:44:38"}]
这是我硬编码到 HTML 中并使用 JSON 更新的表格标记:
<table id="completed_locations" class="table table-striped">
<thead>
<tr>
<th>Location</th>
<th>Completed on</th>
</tr>
</thead>
<tbody>
// JSON data goes here
</tbody>
</table>
我使用此代码构建<tr> 和<td>:
// this is called within success of ajax to build table
var oldTable = document.getElementById('completed_locations'),
newTable = oldTable.cloneNode();
for(var i = 0; i < output.length; i++){
var tr = document.createElement('tr');
for(var j = 0; j < output[i].length; j++){
var td = document.createElement('td');
td.appendChild(document.createTextNode(output[i][j]));
tr.appendChild(td);
}
newTable.appendChild(tr);
}
oldTable.parentNode.replaceChild(newTable, oldTable);
【问题讨论】:
-
Cerbrus 已经指出了您的第一个问题(您有一个 JSON 字符串,您需要解析它以获取实际的 JavaScript 数组)。接下来您需要解决的是创建
<td>元素,如果您有一个对象数组,而不是数组数组,这看起来是错误的。
标签: javascript html json html-table