jquery - 如何迭代特定的json对象

时间:2016-04-30 01:11:48

标签: jquery json

我正在尝试显示来自NYT的返回json对象的结果。它应该显示每篇文章的前几段。我已经设法调用API并显示对象名称和其他两个字符串元素,但我想迭代对象并返回每篇文章的第一段,我该怎么做?

var $nytapi = "http://api.nytimes.com/svc/search/v2/articlesearch.json?q=new+york+times&page=2&sort=oldest&api-key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$.getJSON($nytapi, function(data) {
    var items = [];
    $.each(data, function(key, val) {
        items.push("<li id='" + key + "'>" + val + "</li>");
    });
    console.log(data);
    $("<ul/>", {
        "class": "my-new-list",
        html: items.join("")
    }).appendTo($body);
});

1 个答案:

答案 0 :(得分:0)

$.getJSON($nytapi, function(data)
                        {
                  var items = [];
                  $.each(data.response.docs, function(idx, obj) 
                                    {
                                                items.push( "<li class='article'><a href='" + obj.web_url + "'target='_blank'>" + obj.headline.main + "</a><p>"+obj.snippet+"</p></li>" );
                                    }
                        );
                  $( "<ul/>", 
                          {
                            "class": "my-new-list",
                            html: items.join("")
                          }
                   ).appendTo($nytElem);
               }
         ).error(function() {$nytHeaderElem.text("error");});