0

我正在尝试通过遍历key:valueJSON 对象中的对来创建动态表。

目前我的对象中只有一对,所以我的表格应该只有一个表格行和两个<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.,
4

1 回答 1

1

First, add the json datatype to your .post call

$.post('url',{data:data},successhandler,"json")

Next, remove the $.parseJSON line. Profit. You were looping over a string rather than your parsed json, which would explain the 50 rows of undefined you were seeing (there are 50 characters in your json string)

var gsd = $.post('forumquery_test.php', {
    'postarray': postarray
}, function (result, success) {
    console.log(result);
    $.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);
    })
},"json")
于 2013-07-10T21:06:56.643 回答