php - 数据表不接受 PHP Echo 作为 Data Ajax PHP

标签 php html mysql ajax datatables

我正在使用 PHP 并使用 Datatable 填充我的表用于分页和过滤器。我有一个 Android 应用程序正在将值发送到我的数据库。我想要的是实时更新我的​​表。我尝试使用 AJAX 通过间隔调用 PHP 脚本来使其实时。它工作正常,但分页和过滤器不起作用。

不要介意表格标题

enter image description here

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。 有人可以帮我解决这个问题吗?

最佳答案

每次刷新/重新加载后,您需要重新初始化数据表:

$.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使得重新初始化表而不会出现错误成为可能。

关于php - 数据表不接受 PHP Echo 作为 Data Ajax PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33063768/

相关文章:

php - 如何为 symfony Controller 编写 php 单元测试用例

php - 如何在样式表 Wordpress 中链接背景图片?

javascript - 在内部 div 中捕获滚动

html - 离线 lorem ipsum 生成器

php - 在哪里使用 mysql_real_escape_string 来防止 SQL 注入(inject)?

php - 如何将访问 token 插入MySQL数据库?

php - Doctrine 2 : Call to a member function format() on a non-object . .. 在 DateTimeType.php

html - 仅使用 CSS 固定高度的方形 div

php - mysql 查询中的正则表达式

php - 复制后编码混淆