简体   繁体   English

遍历json ajax响应

[英]Loop through json ajax response

I am trying to create a loop from the json data of an ajax respone. 我正在尝试从ajax respone的json数据创建一个循环。 The json returned is: 返回的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> ",
        }
    ]
}

I using the following code to convert the json data into html markup, my problem is getting a loop going. 我使用以下代码将json数据转换为html标记,我的问题是循环不断。 I would like to output markup for each instance of data 我想为每个数据实例输出标记

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

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

        });
});
</script>

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

You can see the the json data for .posts[0].content is loaded into .content, I would like some help creating a loop with the scenario 您可以看到.posts [0]的json数据。content已加载到.content中,我想为创建场景循环提供一些帮助

Using: 使用方法:

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

Check out the MDN Article on the for..in syntax . 查看有关for..in语法MDN文章 And caching the $('.content') selector in a variable will improve the performance. 并且将$('.content')选择器缓存在变量中将提高性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM