javascript - 如何使用 Ajax 显示 API 数据?
问题描述
我希望能够使用下面代码中的 API 以格式化的方式显示数据,例如这个示例。
Job Title: Agricultural and Related Trades
Percentage of Occupancies in Area: 15.41%
你可以找到我在下面显示数据的糟糕尝试。我对 Ajax、jQuery、JavaScript 等非常陌生。
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(function() {
$.ajax({
url: "http://api.lmiforall.org.uk/api/v1/census/jobs_breakdown?area=55.9895989531941,-3.796229726988194",
type: "get",
dataType: "json",
success: function(data) {
console.log(data[0].area);
outputString= data[0].description.percentage;
var paragraph = $("<p />", {
text: outputString
});
$("body").append(paragraph);
}
});
});
</script>
解决方案
成功执行 GET 请求后,您将在 data 变量中获得响应,现在您可以运行 for 循环来填充预期结果“HTML”文本,而不是将其附加到 HTML 正文中
我这里使用了 JavaScript toFixed()方法,只保留两位小数
$(function() {
$.ajax({
url: "http://api.lmiforall.org.uk/api/v1/census/jobs_breakdown?area=55.9895989531941,-3.796229726988194",
method: "GET",
dataType: "json",
success: function(data) {
var str = "";
for(var i= 0; i < data.jobsBreakdown.length; i++){
str +='Job Title : '+data.jobsBreakdown[i].description+' and Related Trades <br> Percentage of Occupancies in Area : '+data.jobsBreakdown[i].percentage.toPrecision(2)+'% <br><br>';
}
$("body").html(str);
}
});
});
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
推荐阅读
- mysql - 如何以编程方式连接到我的 RDS MySQL 实例?
- c++ - 我无法在不同的线程(C++)中使用 WindowsForms 方法
- android - 如何将音频文件保存到外部存储?
- excel - 用于在 Excel 中更改边框线颜色的 VBA
- c++ - C++ 中基类和派生类对象的树结构
- python - 在上一段的空格后输入文本数据
- prometheus - 为非原因的微服务静音警报
- javascript - 如何在Javascript中获取全局对象的名称和道具
- firebase - 托管中自定义域上的 Firebase 动态链接重写但如何
- javascript - 如何在单击超链接时以弹出模式打开另一个页面