我尝试用ajax源json将数据显示到数据表中,在没有问题之前,但是在我发现嵌套的json数组后,我有点困惑地实现了它,因此我如何将拥有的json应用到数据表中 。这是我的数据
配置数据表
var myTable = $('#myTable').DataTable({
ajax: base_url+"api/data/list",
responsive: true,
columns: [
{ "data": "", "sClass": "text-center", responsivePriority: 0 },
{ "data": "first_name", "sClass": "text-center", responsivePriority: 1 },
{ "data": "last_name", "sClass": "text-left"},
{ "data": "birth_date", "sClass": "text-left", responsivePriority: 2 },
{ "data": "birth_place", "sClass": "text-left" },
],
language: {
searchPlaceholder: 'Search...',
sSearch: '',
zeroRecords: 'No data',
}
})
结果ajax json
{
"data": [
{
"1": {
"first_name": "Jonh",
"last_name": "Connor",
"birth_date": "1991-11-05",
"birth_place": "USA"
},
"2": {
"first_name": "Uka",
"last_name": "Uka",
"birth_date": "2013-01-06",
"birth_place": "Austria"
}
}
]
}
我希望结果如下表
| NO | first_name | last_name | birth_date | birth_place |
| 1 | Jonh | Connor | 1991-11-05 | USA |
| 2 | Uka | Uka | 2013-01-06 | Austria |
答案 0 :(得分:1)
IDK(如果有帮助但...
myTable.data [0] .1.first_name
也许吗?
它包含一个对象,该对象包含包含更多对象的数组。就像JSON起始。
更新:
很确定您在那里进行的ID操作搞砸了。它认为是列名。所以第1列变成第2列。只需将ID放入数据中即可。
尝试一下
HTML
<!DOCTYPE html>
<html>
<head>
<!-- Data Tables -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
</head>
<body>
<p id="demo"></p>
<br/>
<table id=example>
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Birth Date</th>
<th>Birth Place</th>
</tr>
</thead>
</table>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<!-- Data Tables -->
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<script scr="http://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"></script>
</body>
</html>
脚本
let data = {
"data": [
{
"record_id": "1",
"first_name": "Jonh",
"last_name": "Connor",
"birth_date": "1991-11-05",
"birth_place": "USA"
},
{
"record_id": "2",
"first_name": "Uka",
"last_name": "Uka",
"birth_date": "2013-01-06",
"birth_place": "Austria"
}
]
};
$(document).ready(function() {
$('#example').DataTable( {
data: data.data,
columns: [
{ "data": "record_id", "sClass": "text-center", responsivePriority: 0 },
{ "data": "first_name", "sClass": "text-center", responsivePriority: 1 },
{ "data": "last_name", "sClass": "text-left"},
{ "data": "birth_date", "sClass": "text-left", responsivePriority: 2 },
{ "data": "birth_place", "sClass": "text-left" },
]
} );
} );