【发布时间】:2017-12-27 20:54:28
【问题描述】:
我在将一些客户端数据表逻辑迁移到服务器端时遇到了一些困难。
我当前的问题是,对于 Datatables,如果您想对大量数据(20,000 多行)进行分页,我首先需要加载 Controller 中的所有行,然后将它们传递给视图:
$records = \App\Records::get();
return view("example.datatables")->with(["records" => $records]);
接下来,这需要大约 2 分钟的等待时间,然后才能加载所有内容,Datatables 会将记录分页为 500 页:
$("#table").DataTable({
paging: true,
pageLength: 500,
...
});
我已将 Datatables 声明更改为通过 ajax 处理服务器端处理,如下所示:
$("#table").DataTable({
processing: true,
serverSide: true,
ajax: {
url: "...",
type: "GET"
}, paging: true,
pageLength: 500,
...
});
按照我的意愿让它工作已经很顺利了,但问题是 Datatables 覆盖或忽略了我从ajax 请求发回的内容:
$columnData = [];
foreach($recordsFromDatabase AS $record){
$columnDataObject = [];
$columnDataObject[0] = '<td class="myClass" data-property="myProperty"><input type="text" name="customInput[]"/></td>'
...
$columnData[] = $columnDataObject;
}
return response()->json([
"draw" => (int)$request->input("draw"),
"recordsTotal" => $totalRecords,
"recordsFiltered" => $totalFilteredRecords,
"data" => $columnData,
"error" => null
]);
基本上,我发回的是一个包含data 的json 响应,它是一个列数组,它们是<td> 元素,而不仅仅是一个普通值。所以<td>Value</td> vs Value。
Datatables 给人的错觉认为这是正常工作,但我最终得到了
<tr role="row" class="even">
<td class="sorting_1"><input type="text" name="customInput[]"/></td>
...
</tr>
<tr role="row" class="odd">
<td class="sorting_1"><input type="text" name="customInput[]"/></td>
...
</tr>
它正确地呈现了<td> 内部的<input>,但缺少class="myClass" data-property="myProperty",这破坏了我的表的扩展功能。
有什么方法可以告诉 Datatables 我发回的是有效的 <td> 元素,它需要做的就是添加一个 odd 或 even 类? (即便如此,我认为这只是为了造型)。
【问题讨论】:
-
查找laravel分页laravel.com/docs/5.4/pagination
-
这不是 Laravel 分页的问题,也不是一般的分页问题。
-
当您可以使用 laravel 分页类完成所有这些操作时,您不需要数据表,并且使用分页执行此操作通常会加快进程,因为您将处理 x 块而不是 20,000
-
我知道,相信我,我不想仅仅因为这个原因而使用 Datatables,但由于客户的要求,我被锁定了。此外,这是一个非常小众的问题,所以即使 Laravel 分页会产生奇迹,但它对我来说不是一个选择。为这个建议干杯。
标签: php jquery ajax laravel datatables