2016-01-05 116 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)吗?