【发布时间】:2017-08-11 01:17:15
【问题描述】:
我有一个 ajax 函数,它向 api 发送 get 请求并以以下格式返回数据 -
{
"firstname": "John",
"lastname": "Doe",
"email": "doej@gmail.com",
"subjects": [
{
"id": 1,
"name": "maths"
},
{
"id": 2,
"name": "chemistry"
}
]
},
我需要在表格中显示这些数据,但无法正确显示主题数组,即作为一个表格单元格中的列表。我试图将数组数据放入主表中的另一个表中,但没有成功。我认为我在迭代循环中的某个地方出错了。
function getPeople() {
$.ajax({
type: "GET",
url: "http://example.com",
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (data, status, jqXHR) {
// fill a table with the JSON
$("table.mytable").html("<tr><th></th><th>First Name</th><th>Last Name</th><th>Subjects</th></tr>" );
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].subjects.length; j++) {
var subjects = data[i].subjects[j];
$("table.insidetable").append('<tr><td>' + subjects + 'tr><td>')
}
$("table.mytable").append('<tr><td><input type = "checkbox" id = '+data[i].id+'>' + "</td><td>" + data[i].firstname + "</td><td>" + data[i].lastname + "</td><td>" + "table.insidetable" + "</td></tr>");
}
},
error: function (jqXHR, status) {
// error handler
console.log(jqXHR);
alert('fail' + status.code);
}
});
}
【问题讨论】:
-
你的js控制台有错误吗?
-
我认为您需要先使用 JSON.parse() 解析 json 数据
标签: javascript html for-loop html-table