jQuery $ .ajax和$ .each循环遍历数组

时间:2017-09-05 08:29:43

标签: javascript jquery json ajax each

我正在调用纽约时报的文章搜索API,并希望将其作为新的列表元素附加到HTML元素。但是我在使用$ .each()函数并迭代JSON数据时遇到了麻烦。我正在尝试发布超链接和文章片段。

我得到的错误是“$ .each(data,function(i,data.response)”中的data.response中的“Uncaught SyntaxError:Unexpected token”

$.ajax({
  url: url,
  method: 'GET',
}).done(function(data) {
  $.each(data, function(i, data.response){
    $.each(data.response.docs, function(index, object){
      $nytElem.append('<li class ="article">'+
      '<a href='+ data.response.docs[index].web_url +'>' + data.response.docs[index].headline.main +
      '</a><p>' + data.response.docs[index].snippet + '</p></li>')
    });
  });
  console.log(data);
}).fail(function(err) {
  throw err;
});

API返回一个对象,其中包含包含10篇文章信息的数组。为简洁起见,我在这里只发布了2个。任何帮助将不胜感激!

    {
      "status": "OK",
      "copyright": "Copyright (c) 2017 The New York Times Company. All Rights Reserved.",
      "response": {
        "docs": [
          {
            "web_url": "https://www.nytimes.com/aponline/2017/09/05/world/asia/ap-as-taiwan-politics.html",
            "snippet": "Taiwan's president has appointed a new premier seen as willing to reach out to rival China amid ongoing tense relations.",
            "blog": {},
            "source": "AP",
            "multimedia": [],
            "headline": {
              "main": "Taiwan Appoints New Premier Amid Tense China Relations",
              "print_headline": "Taiwan Appoints New Premier Amid Tense China Relations"
            },
            "keywords": [],
            "pub_date": "2017-09-05T06:06:43+0000",
            "document_type": "article",
            "new_desk": "None",
            "section_name": "Asia Pacific",
            "byline": {
              "original": "By THE ASSOCIATED PRESS"
            },
            "type_of_material": "News",
            "_id": "59ae3f007c459f246b621bb9",
            "word_count": 131,
            "score": 1,
            "uri": "nyt://article/ae5b0e41-75b2-5a7e-972d-8a76bcd5c11a"
          },
          {
            "web_url": "https://www.nytimes.com/reuters/2017/09/05/business/05reuters-hyundai-motor-china.html",
            "snippet": "South Korea's Hyundai Motor said it had suspended production at one of its China factories on Tuesday after a supplier refused to provide parts due to delays in payment - its second such incident in as many weeks.",
            "blog": {},
            "source": "Reuters",
            "multimedia": [],
            "headline": {
              "main": "Hyundai Hit Again by Supply Disruption in China, One Plant Halted",
              "print_headline": "Hyundai Hit Again by Supply Disruption in China, One Plant Halted"
            },
            "keywords": [],
            "pub_date": "2017-09-05T06:03:30+0000",
            "document_type": "article",
            "new_desk": "None",
            "byline": {
              "original": "By REUTERS"
            },
            "type_of_material": "News",
            "_id": "59ae3e427c459f246b621bb8",
            "word_count": 516,
            "score": 1,
            "uri": "nyt://article/c519de15-1040-5fc7-b1ad-8e73aed33a47"
          }
       ],
       "meta": {
         "hits": 16210307,
         "offset": 0,
         "time": 1016
        }
     }
  }

1 个答案:

答案 0 :(得分:2)

这就是你所需要的:

.done(function(data) {
    $.each(data.response.docs, function(i, doc) {
        var $a = $('<a>').attr("href", doc.web_url).html(doc.headline.main);
        var $p = $('<p>').html(doc.snippet);
        var $li = $('<li>').addClass("article").append($a).append($p);
        $nytElem.append($li);
    });
});

传递给$.each()的函数的第二个参数将包含您传递的数组的每个元素。所以你做的是传递data.response.docs,这是文章数组,然后使用doc(或类似的)作为参数,doc.[node]来访问数组中的对象及其子项。