我有一个包含近14000条记录的位置表, 我需要对服务器端数据进行ajax分页。 我使用了下面的代码,但是没有用。
<table class="table table-bordered table-striped table-hover dataTable js-exportable" id="htmltableID">
<thead>
<tr>
<th>SNO</th>
<th>Location</th>
<th>City</th>
<th>State</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
foreach ($data as $row) {
echo "<tr>";
echo "<td>" . $i . "</td>";
echo "<td>" . $row->location . "</td>";
echo "<td>" . $row->city . "</td>";
echo "<td>" . $row->state . "</td>";
echo "</tr>";
$i++;
}
?>
</tbody>
</table>
<script>
var oTable = "";
$(document).ready(function () {
oTable = $('#htmltableID').dataTable({
"sPaginationType": "full_numbers",
"bServerSide": true,
"sAjaxSource": "location",
"sServerMethod": "POST",
"iDisplayLength": 5
});
});
</script>
通过使用此代码,我收到错误消息“ DataTables警告:表id = htmltableID-无法重新初始化DataTable。有关此错误的更多信息,请参见http://datatables.net/tn/3”和“ DataTables警告:表id = htmltableID-无效的JSON响应。有关此错误的更多信息,请参见http://datatables.net/tn/1“
答案 0 :(得分:0)
您应该在主文件中具有以下代码类型。假设Maindata.php
<table class="table table-bordered table-striped table-hover dataTable js-exportable" id="htmltableID">
<thead>
<tr>
<th>SNO</th>
<th>Location</th>
<th>City</th>
<th>State</th>
</tr>
</thead>
</table>
<script>
var oTable = "";
$(document).ready(function () {
oTable = $('#htmltableID').dataTable({
"sPaginationType": "full_numbers",
"bServerSide": true,
"sAjaxSource": "location",
"sServerMethod": "POST",
"iDisplayLength": 5
});
});
</script>
需要从其他文件中获取数据(json),例如loadrecords.php
(在您的情况下为location/loadRecord
)
<?php
// $data is the list of records fetched from database
// No need to print the data since we need to provide json data to dataTable, so Below code not required
/*
$i = 1;
foreach ($data as $row) {
echo "<tr>";
echo "<td>" . $i . "</td>";
echo "<td>" . $row->location . "</td>";
echo "<td>" . $row->city . "</td>";
echo "<td>" . $row->state . "</td>";
echo "</tr>";
$i++;
}
*/
// Data which you needs to send in 'location/loadRecord' should be like this (In my case it was `loadrecords.php`)
/*{
"data": [
["1","Location 1","City 1","State 1"],
["2","Location 2","City 2","State 2"],
.....
.....
["N","Location N","City N","State N"]
]
}*/
// Loop the data records fetched from database and prepare array in below format
$json_arr = array(
"data" => array(
array("1","Location 1","City 1","State 1"),
array("2","Location 2","City 2","State 2"),
...............
...............
array("N","Location N","City N","State N"),
)
);
echo json_encode($json_arr);
数据将具有4列的N个行数,因为您要在表中显示4列,因此需要在json中提供相关数据