我想像这样通过ajax加载数据表link
我的ajax数据源是这样的
$result = DB::table('test')->get();
$test = [];
$i=0;
foreach ($result as $row):
$test[$i]['id'] = "-";
$test[$i]['kode'] = $row->kode;
$test[$i]['date'] = $row->date;
$test[$i]['name'] = $row->name;
$test[$i]['total'] = $row->total;
$test[$i]['payment'] = $row->payment;
$i++;
endforeach;
return json_encode(['aaData' => $test]);
但我无法访问初始化数据表中的数据
var dTable = $('#dataTable').DataTable({
"processing": true,
"serverSide": true,
"sAjaxSource": "{{ URL::route('list.laporan.pembelian') }}",
"columnDefs": [
{ "targets": 0, "className": 'details-control', "orderable": false, "data": null, "defaultContent": '' },
{ "data": "kode", "name" : "kode" },
{ "data": "date", "name" : "date" },
{ "data": "name", "name" : "name" },
{ "data": "total", "name" : "total" },
{ "data": "payment", "name" : "payment" }
]
});
我尝试使用此脚本打印数据是否成功加载到 console.log
中
dTable.on( 'xhr', function ( e, settings, json ) {
console.log( 'Ajax event occurred. Returned data: ', json );
});
它给出的结果是这样的
object
aaData:Array[2]
[0]:object
id: "-"
kode: "Pl001"
date: "01/01/2015"
name: "test1"
total: "$12"
payment: "credit"
[1]:object
id: "-"
kode: "Pl002"
date: "01/02/2015"
name: "test2"
total: "$3"
payment: "credit"
我认为这意味着我已经成功加载数据..
但为什么我仍然无法访问它?
更新@ivar
最佳答案
我认为您返回数据的方式不正确。看看Server-side processing page数据表网站的。
您应该返回的数据应该是:
- draw(此对象响应的
draw
计数器 - 来自作为数据请求的一部分发送的绘制参数。) - recordsTotal(过滤前的记录总数(即数据库中的记录总数))
- recordsFiltered(过滤后的总记录数(即应用过滤后的记录总数 - 不仅仅是此数据页返回的记录数)。)
- data(一组数据源对象,每一行一个)
我将添加我如何使用 Ajax 实现它:
表:
<table id="dataTables-table">
<thead>
<tr>
<th id="col1">col1name</th>
<th id="col2">col2name</th>
<th id="col2">col2name</th>
</tr>
</thead>
<tbody></tbody>
</table>
Javascript:
$('#dataTables-table').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"type": "POST",
"url": "url/to/page"
},
"columns": [
{ "name": "col1", "data": "col1" },
{ "name": "col1", "data": "col1" },
{ "name": "col1", "data": "col1" }
]
});
关于javascript - 数据表加载数据成功但无法通过名称访问它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35088045/