循环通过json ajax响应

时间:2015-05-18 20:34:33

标签: jquery ajax json

我正在尝试从ajax respone的json数据创建一个循环。返回的json是:

{
    status: "ok",
    count: 2,
    count_total: 2,
    pages: 1,
    posts: [
        {
            id: 19,
            content: "<p>Dektop Test 2</p> ",
        },
        {
            id: 11,
            content: "<p>Desktop Test</p> ",
        }
    ]
}

我使用以下代码将json数据转换为html标记,我的问题是循环进行。我想为每个数据实例输出标记

<script>
jQuery(function($) {
    $.getJSON('theurlforjson')
        .success(function(response) {

            var $title = $('.content').html(response.posts[0].content);

        });
});
</script>

<div class="content"></div>

你可以看到.posts [0] .content的json数据加载到.content中,我想帮助创建一个带有场景的循环

1 个答案:

答案 0 :(得分:2)

使用:

for( var post in response.posts ){
    $('.content').append( response.posts[post].content );
}

查看MDN Article on the for..in syntax。在变量中缓存$('.content')选择器可以提高性能。