【发布时间】:2013-07-11 05:12:03
【问题描述】:
我正在尝试通过遍历 JSON 对象中的 key:value 对来创建动态表。
目前我的对象中只有一对,所以我的表格应该只有一个表格行,其中包含两个 <td> 单元格,但是我得到 30 多行,每行包含两个包含 "undefined" 作为文本的单元格。不知道是什么原因造成的。
HTML:
<div class="posts">
<table><h2>Posts from My Leaders</h2>
<tr>
<th></th>
<th></th>
</tr>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
</div>
jQuery:
var gsd = $.post('forumquery_test.php', {'postarray' : postarray}, function(result, success) {
console.log(result);
var json = $.parseJSON(result); //[{"Username":"stan","Post_txt":"Hi, this is Stan"}]
console.log(json[0].Post_txt); //Hi, this is Stan
console.log(json[0].Username); //stan
$.each(result, function(index, value) {
var username = value.Username;
var posttxt = value.Post_txt;
var newrow = '<tr><td>'+username+'</td><td>'+posttxt+'</td></tr>';
$('.posts table').append(newrow);
})
})
结果:
Username Post
undefined undefined
undefined undefined
etc., etc.,
【问题讨论】: