Javascript 如何使用AJAX Jquery获取API?

Javascript 如何使用AJAX Jquery获取API?,javascript,jquery,json,ajax,Javascript,Jquery,Json,Ajax,如何使用JSON AJAX Jquery从API获取数据 我想通过一个简单的json ajax jquery方法获得完整的数据 我仍然不知道如何以简单的方式获取API数据 当我想要获取数据时,我会得到未定义的数据 下面是我的代码: <html> <head> <title>Index</title> <script type="text/javascript" src="https://ajax.googleapis.com/

如何使用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>

要解析数据,您需要了解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
}
此代码段有一些更改,您可以通过查看上面的结构来理解这些更改。 指数 变量url=https://api.stackexchange.com/2.2/tags/jquery/top-answerers/all_time?site=stackoverflow; $.getJSONurl,functionresult{ console.logresult //循环浏览结果。项目不是结果 $.eachresult.items、functioni、data{ var user\u id=data.user.user\u id;//不是data.user\u id var profile\u image=data.user.profile\u image;//不是data.profile\u image var post_count=data.post_count; var得分=data.score; $listview.append` UserID:${user\u id} Post计数:${Post_计数} 分数:${Score} `; }; };
在代码中添加一些文本是一种很好的做法,以使查看者理解它的功能。@QuickSilver我很感谢您的建议,但我不太明白。也许,你可以告诉我在哪里或者怎样做。