使用'加载更多选项'在jQuery中解析json

时间:2011-10-05 16:09:05

标签: html jquery jquery-plugins

我在jquery中有有效的数据,如何循环我收到的每个项目并在html容器div中显示它。谢谢

第1项   图片123 第2项  图123

{"ERRORS":[],"DATA":[{"itemValidFrom":"October, 25 2011 00:00:00","itemActive":true,"itemTxt":"test","itemID":"30d2f2c1-58ca-4b3d-b3e0-d284ae5b25ab","itemValidTo":"October, 19 2011 00:00:00","itemName":"test","itemModified":"October, 05 2011 00:00:00","itemCreated":"October, 03 2011 00:00:00","image":{"imageCreated":"October, 05 2011 00:00:00","imageURL":"firefox-girl.jpg","imageID":"bc869a94-fee5-4fc8-bd21-e2de2f020310"}],"MESSAGES":[{"CURRENTPAGE":1.0,"TOTALPAGES":1.0}]}

<script type="text/javascript">
    jQuery(document).ready(function(){

    jQuery.ajax({
    type: 'get',
    url: 'api/default.php/id/0f4addd8',
    data: 'apiKeytest=182j&?perPage=2&currentPage=1',
    dataType: "json",
    context: document.body,
    success: function(r) {
    jQuery('#posts-container').replaceWith(r);
            console.log(r);
                        }

    });

    });

</script>


<!-- Widget HTML Starts Here -->
<div id="posts-container">
    <!-- Posts go inside this DIV -->
    <div id="posts"></div>
    <!-- Load More "Link" -->
    <div id="load-more">Load More</div>
</div>
<!-- Widget HTML Ends Here -->

1 个答案:

答案 0 :(得分:0)

您可以使用for循环遍历json数据并构建自定义输出以附加到DOM:

success: function(r) {
    var output = '';
    for (a in r.DATA) {
        for (b in r.DATA[a]) {
            if (typeof(r.DATA[a][b]) == 'object') {
                for (c in r.DATA[a][b]) {
                    output += c + ' = ' + r.DATA[a][b][c] + '<br />';
                }
            } else {
                output += b + ' = ' + r.DATA[a][b] + '<br />';
            }
        }
    }
    jQuery('#posts-container').append(output);
}

a对应于ajax调用返回的对象中的每个键。

我创建了上面代码的jsfiddle并注意到你在问题中发布的json输出中有错误;从}数组(只有一个键DATA)的末尾省略了右括号(0)。

以下是jsfiddle的链接:http://jsfiddle.net/EpjyH/1/