javascript - Print Json data in html tabel by javascript
问题描述
I have JSON data saved in this api https://api.myjson.com/bins/xeza2
. I want to print the data in a table by using only JavaScript or jQuery. I have tried a few things. I have used XMLHTTP request. Json.parse() . Every method on stack.
This was the first thing I have tried
$(function () {
var people = [];
$.getJSON('https://api.myjson.com/bins/xeza2', function (data) {
$.each(data.info, function (i, f) {
var tblRow = "<tr>" + "<td>" + f.id + "</td>" +
"<td>" + f.name + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
});
});
});
解决方案
data.info
这就是undefined
为什么您没有在表格中添加任何内容的原因。您需要将其更改为data.ct_info
.
以下代码可以访问请求响应中的 JSON 数据并将其附加到表中。我不确定您希望数据的外观或您尝试访问的属性(因此是undefined
's),我将留给您,但以下内容应该可以帮助您入门。
f.job
并且f.roll
是不存在的属性。
$(function() {
var people = [];
$.getJSON('https://api.myjson.com/bins/xeza2', function(data) {
$.each(data.ct_info, function(i, f) {
var tblRow = "<tr>" + `<td id=${f.id}>` + "</td>" +
"<td>" + f.name + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
var users = []
//GET USER INFO
f.Qid_info.forEach((x) => {
x.user_info.forEach((y) => {
//avoid duplicates
var foundUser = users.find((user) => {
return user.id === y.id
})
if (!foundUser) {
users.push(y)
}
})
})
$.each(users, function(i, user) {
var userRow = "<tr>" + `<td id=${user.id}>` + "User's Name:" +
"</td>" +
"<td>" + user.name + "</td>" + "</tr>"
$(userRow).appendTo("#userdata tbody");
})
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='userdata'>
<tbody>
</tbody>
</table>
推荐阅读
- machine-learning - 评分和索引如何在信息检索系统中协同工作
- amazon-web-services - Boto S3 URL 生成
- python - Django 不在 TestCase 上发送电子邮件,但它在 Shell 上发送
- python-3.x - Pandas groupby 数据框然后返回单值结果(总和,总计)
- sparql - DBPedia 从足球俱乐部加载摘要
- php - 如何通过绑定到文本字段( input-group )来拒绝用户输入并允许从下拉列表中输入( input-group-btn )
- rest - Convertto-Json 不存在文件内容
- javascript - Node 中的抓取数据不会出现在 HTML 页面中
- python - 为调用静态方法的类中的方法编写单元测试
- python - 为什么 myVar = strings.Fields(scanner.Text()) 比 python 中的类似操作花费更多时间?