javascript - 如何使用 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>
解决方案
要解析数据,您需要了解 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>
推荐阅读
- c# - 如何通过变量设置 CompositionObject
- visual-studio-code - 用vscode和wsl调试时找不到pipeTransport程序
- javascript - 有没有更好的方法来避免或编写更少的防御性代码?
- thinkscript - 如何在 thinkscript 中输出/打印?
- r - 当数字列上的键和从文件中读取的数据时,键控 data.table 的 X[Y] 连接失败
- sql-server - 工作经历可以延长吗?
- c - 关于 POSIX 消息队列和无效参数
- visual-studio-code - 在 VSC 中“找到可分组关系“OneToOne”是什么意思?
- php - $guard 是做什么的
- reactjs - 如何在 ReactJS 中将 Firebase Auth 类组件生命周期转换为 Hooks useEffect?