我尝试动态构建HTML表格是徒劳的。 代码工作,但它不输出我所需要的。 只有2我的JSON输出中的属性:location
和completed_on
非但没有这样的:如何使用来自AJAX调用的JSON数据构建表?
+-------------------+---------------------+
| Location | Completed on |
+-------------------+---------------------+
| 10 Duskwood Dr. | 2015-07-06 14:10:42 |
| 2 Booty Bay Blvd. | 2015-07-09 13:44:38 |
+-------------------+---------------------+
代码显示了这一点(没有THEAD可见):
[
{
"
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数组)。接下来你需要修正的是''元素的创建,如果你有一个对象数组,而不是一个数组数组,那么这个元素看起来是错误的。 –