无法从ajax请求中获取json数据以在html中显示

时间:2016-01-05 23:34:33

标签: jquery json ajax api

我正在尝试使用“纽约时报”畅销书列表API来列出html中当前的前20名 - 我已经设法使用ajax检索数据(我可以使用开发人员工具查看它)但是却遇到了困难让它显示在页面上。我没有收到任何错误消息 - 没有任何反应。这是我的代码:

<!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>

关于我做错了什么的暗示? 感谢

2 个答案:

答案 0 :(得分: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>');
  }
}

答案 1 :(得分:0)

在使用其元素之前,你不必调用JSON.parse(响应)吗?

相关问题