【问题标题】:Dynamic table with .each() method带有 .each() 方法的动态表
【发布时间】: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.,

【问题讨论】:

    标签: jquery html


    【解决方案1】:

    首先,将 json 数据类型添加到您的 .post 调用中

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

    接下来,删除 $.parseJSON 行。利润。你循环的是一个字符串而不是你解析的 json,这可以解释你看到的 50 行 undefined (你的 json 字符串中有 50 个字符)

    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")
    

    【讨论】:

    • 是的,这行得通。如果我理解的话,.post 调用返回了一个 JSON 对象,而 .parseJSON 将其解析为一个字符串,这就是我的问题?
    • 不,您解析了返回到存储在名为json 的变量中的对象的 JSON 字符串,但从未使用过它。您改为继续使用 result ,它仍然是一个 json 字符串。如果您在使用 $.each 的地方将 result 替换为 json,那么您的原始代码将可以工作。
    • 是的,现在我明白了。这就是为什么它在其他地方对我有用,而不是在这里。谢谢。
    猜你喜欢
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 2012-12-07
    • 2019-12-13
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    相关资源
    最近更新 更多