【发布时间】:2020-07-03 04:57:16
【问题描述】:
我有一个使用 DataTables 的表格,它包含大量行,因此这会导致页面加载非常缓慢,因为我假设浏览器会等到表格填满后再显示页面。
我只想加载表格的一页(10 行),并且只在用户浏览表格时显示更多数据,显示加载标志也很好。
我研究并听说了一个名为“deferRender”的 DataTables 函数,它应该可以满足我的需求,但我无法让它与我的表一起使用。
我的表格有 8 列 + html 是使用 PHP 生成的,它从文本文件中的数据构建表格:
<?php
$tdcount = 1; $numtd = 8; // number of cells per row
$str = "<table id=\"table1\" class=\"table1 table table-striped table-bordered\">
<thead>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>6</th>
<th>7</th>
<th>8</th>
</thead>
<tbody>
";
$f = fopen("tabledata.txt", "r");
if ( $f === FALSE ) {
exit;
}
while (!feof($f)) {
$arrM = explode(",",fgets($f));
$row = current ( $arrM );
if ($tdcount == 1)
$str .= "<tr>"; $str .= "<td>$row </td>";
if ($tdcount == $numtd) {
$str .= "</tr>";
$tdcount = 1;
} else {
$tdcount++;
}
}
if ($tdcount!= 1) {
while ($tdcount <= $numtd) {
$str .= "<td> </td>"; $tdcount++;
} $str .= "</tr>";
}
$str .= "</tbody></table>";
echo $str;
然后我用下面的代码把它变成一个数据表:
<script>
$(document).ready(function() {
$('#table1').basictable({
forceResponsive: false
});
$('#table1').DataTable( { "order": [[ 0, "desc" ]] } );
});
</script>
我已阅读此处的说明:https://datatables.net/examples/server_side/defer_loading.html 并且知道我需要向 JS 添加参数:
"processing": true,
"serverSide": true,
"ajax": "scripts/server_processing.php",
"deferLoading": 57
并使用 server_processing 脚本,但是该示例仅显示如何在连接到数据库时使用它,而不是在使用 php 从文本文件加载数据时使用它。
我怎样才能做到这一点?
【问题讨论】:
-
您的数据是存储在数据库中还是存储在文件中有些偶然 - 您需要实现以支持 DataTables 的核心服务器端处理大致相同。查看从 DataTables 自动传递到您的服务器的数据结构(在 Sent Parameters 部分中描述)。并查看您需要填充并传递回 DataTables 作为响应的数据结构(在Returned Data 部分中描述)。
-
只是补充一点:“延迟加载”是一种额外的方式来优化您的服务器端处理 - 但它不是服务器端处理工作方式的核心。如果我的笔记没有帮助,我可以提供更长的答案 - 但请查看上面的链接,以及最简单的服务器端案例的数据结构。这应该有助于为您指明正确的方向。如果我没有抓住重点,当然可以告诉我!
-
谢谢,这确实有点帮助,但是如果你能为我的问题提供一个很好的详细解决方案,我仍然对如何做到这一点感到困惑@andrewjames
标签: javascript php ajax datatables