首页 > 解决方案 > 如何使用 AJAX Jquery 获取 API?

问题描述

如何使用 JSON AJAX Jquery 从 API 获取数据?

我想用一个简单的 json ajax jquery 方法获取完整数据

我仍然不知道如何以简单的方式获取 API 数据

当我想获取数据时,我得到未定义

在我的代码下面:

<html>
<head>
    <title>Index</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
        $(document).ready(function()
         {
            var url="https://api.stackexchange.com/2.2/tags/jquery/top-answerers/all_time?site=stackoverflow";
            $.getJSON(url,function(result){
                $.each(result, function(i, data){
                    var user_id=data.user_id;
                    var profile_image=data.profile_image;
                    var post_count=data.post_count;
                    var score=data.score;
                    $("#listview").append("<img src='"+ profile_image +"'>" + user_id + post_count + score);
                });
            });
         });
    </script>
</head>

<body>
    <div id="listview">

    </div>
</body>
</html>

标签: javascriptjqueryjsonajax

解决方案


要解析数据,您需要了解 API 的数据结构。

{
  items: [
    {
      post_count,
      score,
      user: {
        accept_rate,
        display_name,
        link, // To profile page
        profile_image, // A URL
        reputation,
        user_id, // A Number
        user_type // E.G. "moderator"
      }
    },
    // More of the sample object above.
  ],
  quota_max,
  quote_remaining
}

此代码段有一些更改,您可以通过查看上面的结构来理解这些更改。

<html>
<head>
    <title>Index</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
      var url="https://api.stackexchange.com/2.2/tags/jquery/top-answerers/all_time?site=stackoverflow";
      $.getJSON(url,function(result){
      console.log(result)
        // loop through results.items NOT results
        $.each(result.items, function(i, data){
          var user_id=data.user.user_id; // NOT data.user_id
          var profile_image=data.user.profile_image; // NOT data.profile_image
          var post_count=data.post_count;
          var score=data.score;
          $("#listview").append(`
          <table>
          <tr>
          <td><img src="${profile_image}"></td>
          <td>
            UserID: ${user_id}<br/>
            Post Count: ${post_count}<br/>
            Score: ${score}
          </td>
          </tr>
          </table>
          `);
        });
      });
    </script>
</head>

<body>
    <div id="listview">

    </div>
</body>
</html>


推荐阅读