所以我有一个包含json数据的表,我希望使用Datables以表格形式显示这些数据。
问题是列名应该取自json的键, 我会像这样得到json
sql =从data_storage中选择数据,其中layout id = 1
{"text-1488375965148":"Rohan","textarea-1488376086684":"Some addresse","top-search":"","text-1488375966552":"rohan@gmail.com"}
{"text-1488375965148":"Vikram","textarea-1488376086684":"Hello hello hello","top-search":"","text-1488375966552":"vikrambanand@gmail.com"}
{"text-1488375965148":"Ruchita","textarea-1488376086684":"bangalore","top-search":"","text-1488375966552":"Ruchita@gmail.com"}
正如您所看到的,上面查询的json格式是相同的,所以我想以表格的形式显示它们,表格应该是这样的。
<table>
<thead>
<tr>
<th>text-1488375965148</th>
<th>textarea-1488376086684</th>
<th>text-1488375966552</th>
</tr>
</thead>
<tbody></tbody>
</table>
知道如何实现它吗?
答案 0 :(得分:1)
简单地循环您的JSON数据并将数据附加到表:
var jsonData = [{
"text-1488375965148": "Rohan",
"textarea-1488376086684": "Some addresse",
"top-search": "",
"text-1488375966552": "rohan@gmail.com"
},
{
"text-1488375965148": "Vikram",
"textarea-1488376086684": "Hello hello hello",
"top-search": "",
"text-1488375966552": "vikrambanand@gmail.com"
},
{
"text-1488375965148": "Ruchita",
"textarea-1488376086684": "bangalore",
"top-search": "",
"text-1488375966552": "Ruchita@gmail.com"
}
];
var head = $('table thead');
var body = $('table tbody');
var row = '';
row += '<tr>';
$.each(jsonData[0], function(k, v) {
row += '<th>' + k + '</th>';
});
row += '</tr>';
head.append(row);
$.each(jsonData, function() {
row = '<tr>';
$.each(this, function(k, v) {
row += '<td>' + v + '</td>';
});
row += '</tr>';
head.append(row);
})
td, th {
border: 1px solid #ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
</thead>
<tbody>
</tbody>
</table>