我正在使用PHP填充表格,并使用Datatable进行分页和过滤。我有一个Android应用程序正在向我的数据库发送值。我想要的是对我的表进行实时更新。我尝试使用AJAX通过间隔调用PHP脚本来实现它。它工作正常,但分页和过滤器无效。
不介意表标题
HTML代码
<table class="table table-bordered table-hover" id="myTable">
<thead>
<tr class="info">
<th>#</th>
<th>Resident</th>
<th>Complaints</th>
<th>Location</th>
<th>Date Issued</th>
</tr>
</thead>
<tbody id="comTbl">
</tbody>
</table>
<script>
的JavaScript
$(document).ready(function() {
$("#comTbl").load("fetchPresident.php");
var refreshId = setInterval(function() {
$("#comTbl").load('fetchPresident.php?randval='+ Math.random());
}, 9000);
$.ajaxSetup({ cache: false });
});
</script>
<script>
$(document).ready(function() {
$('#myTable').DataTable( {
"lengthMenu": [[5, 10, 25, -1], [5, 10, 25, "All"]]
});
});
</script>
PHP
<?php
//Connect to database
$connection = mysqli_connect('localhost','root','','brm_dbs');
if (!$connection) {
die('Could not connect to database ' . mysqli_error($connection));
}
//Fetch the data from tables
$query="SELECT * FROM presidents";
$result = mysqli_query($connection,$query);
while($row = mysqli_fetch_array($result)) {
echo "<tr><td>" . $row['f_name']."</td>
<td>" . $row['l_name'] . "</td>
<td>" . $row['party'] . "</td>
<td>" . $row['joined_office'] . "</td>
<td>" . $row['left_office'] . "</td>
</tr>";
}
// $output[] = array ("<tbody> <tr>","<td>",$row[0],"</td>","<td>",$row[1],"</td>","<td>",$row[2],"</td>","<td>",$row[3],"<td>","<td>",$row[4],"</td>","</tr> </tbdoy>");
//Close database connection
mysqli_close($connection);
?>
已经尝试回应表格,但数据表无法读取 ID 。 有人可以帮我这个吗?
答案 0 :(得分:1)
每次刷新/重新加载后,您需要重新初始化dataTable:
$.ajaxSetup({ cache: false });
function loadTable() {
$("#comTbl").load("fetchPresident.php");
$('#myTable').DataTable({
destroy: true,
lengthMenu: [[5, 10, 25, -1], [5, 10, 25, "All"]]
})
}
loadTable();
var refreshId = setInterval(function() {
loadTable()
}, 9000);
destroy
可以毫无错误地重新初始化表格。