我正在尝试在表中打印JSON数组。这是我的代码。有什么建议么?提前致谢。
[
{
"id": 1,
"name": "name1",
"age": 10,
"feedback": "feedback1"
},
{
"id": 2,
"name": "name2",
"age": 90,
"feedback": "feedback2"
},
{
"id": 3,
"name": "name3",
"age": 30,
"feedback": "feedback3"
},
{
"id": 4,
"name": "name4",
"age": 50,
"feedback": "feedback4"
}
]
var fileName = "";
function GridLibrary(fileName) {
this.fileName = fileName;
}
GridLibrary.prototype = {
set_fileName: function(fileName) {
this.fileName = fileName;
},
get_fileName: function() {
return this.fileName;
}
};
GridLibrary.prototype.display = function() {
$.ajax({
url: this.get_fileName(),
error: function(that, e) {
console.log(e);
},
success: function(data) {
// printing the keys
var Mytable = "<table>";
$.each(data[0], function(key, value) {
$('body').append('<tr><td id="div' + key + '" </td></tr>');
$('#div' + key).append(key);
});
// printing the rest
$.each(data, function(index, MyList) {
$.each(MyList, function(key, value) {
$('#div' + key).append(" " + MyList[key] + " ");
});
});
Mytable += '</table>';
$('body').append(Mytable);
}
});
};
输出是
id 1 2 3 4
name name1 name2 name3 name4
age 10 90 30 50
feedback feedback1 feedback2 feedback3 feedback4
但我希望它像
id name age feedback
1 name1 10 feedback1
2 name2 90 feedback2
3 name3 30 feedback3
4 nanme4 50 feedback4
最佳答案
您可以尝试一下:
var table = [{
"id": 1,
"name": "name1",
"age": 10,
"feedback": "feedback1"
}, {
"id": 2,
"name": "name2",
"age": 90,
"feedback": "feedback2"
}, {
"id": 3,
"name": "name3",
"age": 30,
"feedback": "feedback3"
}, {
"id": 4,
"name": "name4",
"age": 50,
"feedback": "feedback4"
}];
function addTable(tableData) {
var table = $('<table>');
var tableHeading = $('<tr>');
for (var title in tableData[0]){
if (! tableData[0].hasOwnProperty(title))
continue;
var headingColumn = $('<th>'+ title +'</th>');
headingColumn.appendTo(tableHeading);
}
tableHeading.appendTo(table);
tableData.forEach((rowData)=>{
var row = $('<tr>');
for (var columnData in rowData) {
if (! rowData.hasOwnProperty(columnData))
continue;
var column = $('<td>' + rowData[columnData] + '</td>');
column.appendTo(row);
}
row.appendTo(table);
});
table.appendTo('body');
}
addTable(table);
小提琴:https://jsfiddle.net/41g8g9Lc/1/
请注意,这不会检查以确保每行中的列数相同。如果需要,可以添加这种处理。