2016-01-05 118 views
0

我想使用紐約時報暢銷書列表API來列出當前在HTML中的前20位 - 我設法檢索數據使用AJAX(我可以看到它使用開發人員工具),但一直試圖讓它顯示在頁面上。我沒有收到任何錯誤消息 - 沒有任何反應。這是我的代碼原因:無法獲取JSON數據從Ajax請求顯示在HTML

<!DOCTYPE HTML> 
<html> 

    <head> 
     <title>Discover Books</title> 
     <link rel="stylesheet" type="text/css" href="stylesheet.css"> 
     <meta charset="UTF-8"> 
     <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script> 

    <div id='books'> 
    </div> 


    </head> 

<script> 
    $(document).ready(function(){ 
    $.ajax ({ 
      type: 'GET', 
     dataType: 'json', 
     url: 'http://api.nytimes.com/svc/books/v3/lists/hardcover-fiction?api-key=*API_KEY*', 

     success: function(response){ 
      console.log(response); 
      for(var i = 0; i < response.length; i++) { 
      var listing = response[i]; 
      $('#books').append('<h3>' + title + '</h3>'); 
      } 
     }, 
     error: function(xhr, status, error){ 
      console.log(status); 
      console.log(error); 
     } 
    }); 
    }) 
</script> 

</html> 

任何提示,我做錯了什麼? 謝謝

+0

它是否默認爲錯誤功能? – Derek

+1

不要把你的API密鑰放在代碼示例中。我不知道這個API如何工作,但它通常是一個壞主意。 – dan08

回答

1

title未定義在你的成功函數中。你應該參考listing.title

success: function(response){ 
    console.log(response); 
    for(var i = 0; i < response.length; i++) { 
    var listing = response[i]; 
    $('#books').append('<h3>' + listing.title + '</h3>'); 
    } 
} 

並且看着API響應,您需要向下鑽取到JSON以獲取書籍。

success: function(response){ 
    console.log(response); 
    books = response.results.books; //You may need to tinker with this 
    for(var i = 0; i < books.length; i++) { 
    var listing = books[i]; 
    $('#books').append('<h3>' + listing.title + '</h3>'); 
    } 
} 
+0

非常感謝您解決了這個問題!我一直堅持了幾個小時...... –

+0

嘿,如果你是爲這個API密鑰付錢,或者你關心它的安全性,你可能想要一個新密碼。 – dan08

0

在使用它的元素之前,你不必調用JSON.parse(response)嗎?