2016-04-13 32 views
0

我正在使用jquery嘗試瀏覽紐約時報api。我連接到服務器並獲得JSON響應,但是我無法正確地遍歷JSON對象,並且我的項目中沒有任何內容。
這是我的代碼:
如何瀏覽NYT API JSON返回?

 var url = "http://api.nytimes.com/svc/search/v2/articlesearch.json?q=new york&page=1&api-key=9e4043438fa8df45282e8e570e9ac5ed:5:74988126"; 
$.getJSON(url, function (data) { 
    var items = []; 
    $.each(data, function(key, val){ 
     items.push("<li> <a href='" + response.docs[0].web_url + "' >" + response.docs[0].abstract + "</a>" + "<p>" + response.docs[0].snippet + "</p>"); 
    }); 
    console.log(items); 
}); 

這裏有一個鏈接到紐約時報API指南:http://developer.nytimes.com/docs/read/article_search_api_v2
什麼我做錯了,我該如何解決?
非常感謝您的時間,精力和幫助。

+0

這裏有什麼反應??? – nisar

回答

0

試試這個:

$.getJSON(url, function (data) { 
     data.response.docs.forEach(function(d){ 
      items.push("<li> <a href='" + d.web_url + "' >" + d.abstract + "</a>" + "<p>" + d.snippet + "</p>"); 
     } 
    }); 
0

correted代碼工作..

<!DOCTYPE html> 
<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> 
<script> 
$(document).ready(function(){ 
    $("button").click(function(){ 
     $.getJSON("http://api.nytimes.com/svc/search/v2/articlesearch.json?q=new york&page=1&api-key=9e4043438fa8df45282e8e570e9ac5ed:5:74988126", function(result){ 
     var items = []; 
      $.each(result, function(i, field){ 
       items.push("<li> <a href='" + result.response.docs[0].web_url + "' >" + result.response.docs[0].abstract + "</a>" + "<p>" + result.response.docs[0].snippet + "</p>"); 
alert(result.response.docs[0].web_url); 
      }); 
     }); 
    }); 
}); 
</script> 
</head> 
<body> 

<button>Get JSON data</button> 

<div></div> 

</body> 
</html>