我有使用Ajax填充数据表的javascript函数。我的javascript代码如下:
$('#results').dataTable({
// Ajax load data
"ajax": {
"url": "get_intl_tickets",
"type": "POST",
"data": {
"user_id": 451,
"csrfmiddlewaretoken" : csrftoken,
}
}
})
我在django中的服务器端脚本有一个加载大约500个数据行的函数。现在的问题是我不想一次加载整个数据。相反,我希望有前10个数据行。然后用分页,另外10行像那样。
我阅读了数据表的server side processing页面文档。我也尝试使用"serverSide": true
选项。我不了解服务器端脚本。给出了PHP的一个例子。似乎他们没有使用draw, recordsFiltered, recordsTotal
之类的任何参数。他们在那里使用了php SSP类。它不知道它做了什么。我正试图在django中实现它。
但我没有找到适当的好文档来实现。任何帮助将不胜感激。
答案 0 :(得分:1)
老问题,但我也出奇地难以找到答案,所以万一其他人最终来到这里......:P
我发现这篇 2020 年的文章非常有帮助,特别是第 6 部分展示了“完整代码”,其中包括获取正确的变量、构建 SQL 查询以及如何构建/构造它响应的数据对象: https://makitweb.com/datatables-ajax-pagination-with-search-and-sort-php/
他们的例子贴在下面:
<?php
## Database configuration
include 'config.php';
## Read value
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = mysqli_real_escape_string($con,$_POST['search']['value']); // Search value
## Search
$searchQuery = " ";
if($searchValue != ''){
$searchQuery = " and (emp_name like '%".$searchValue."%' or
email like '%".$searchValue."%' or
city like'%".$searchValue."%' ) ";
}
## Total number of records without filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee");
$records = mysqli_fetch_assoc($sel);
$totalRecords = $records['allcount'];
## Total number of record with filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee WHERE 1 ".$searchQuery);
$records = mysqli_fetch_assoc($sel);
$totalRecordwithFilter = $records['allcount'];
## Fetch records
$empQuery = "select * from employee WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$empRecords = mysqli_query($con, $empQuery);
$data = array();
while ($row = mysqli_fetch_assoc($empRecords)) {
$data[] = array(
"emp_name"=>$row['emp_name'],
"email"=>$row['email'],
"gender"=>$row['gender'],
"salary"=>$row['salary'],
"city"=>$row['city']
);
}
## Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data
);
echo json_encode($response);
答案 1 :(得分:0)
很好的例子: https://datatables.net/examples/server_side/defer_loading.html
但是你需要编辑服务器端。 响应演示
{ 得出:2, recordsFiltered:57, recordsTotal:57 }