表中自动刷新时出现问题

Trouble with auto refresh in table

本文关键字:问题 刷新      更新时间:2023-09-26

我有这个index.php文件来显示循环表中的一些东西:

$sql = 'SELECT id FROM usertbl';
$stmt = $hund->runQuery($sql);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);
<?php foreach ($row as $runloop) { ?>
<table><th> <?php echo $runloop['id']; ?> </th></table>
<?php } ?>

但是,我希望这些表具有自动刷新。所以我有这个新文件data.php和一个更新的index.php

数据.php:

$sql = 'SELECT id FROM usertbl';
$stmt = $hund->runQuery($sql);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);
print_r($row);

索引.php:

   <div id="show"></div>
   <script type="text/javascript">
      $(document).ready(function() {
        setInterval(function () {
            $('#show').load('data.php')
        }, 3000);
    });
   </script>
   <?php foreach ($row as $runloop) { ?>
   <table><th> <?php echo $runloop['id']; </th></table>
   <?php } ?>

这将刷新并打印上述<div>中的输出:

<div class="show"></div>

它工作得很好,但我真的不知道如何把它放在表的循环中,就像第一个index.php文件一样。对此事的方向有什么建议吗?

您可以使用 ajax 调用 data.php 并以 json 格式返回响应以获得更好的方法

尝试:.js

function populate(){
var items= [];
$.ajax({
 url: 'data.php',
 type: 'GET',
 dataType: 'json',
 success: function(data){
    //do something with data here
      console.log(data);
    //loop through data and push to array
    $.each(data, function(i,v){
       items.push('< th >'+v+'< /th >');
    });       
    //join array and append to table
    $('#sampleTable tbody').html(items.join(','));
    },
 error: function(err){
     console.log(err.responseText);
    }
});
}
//call populate every 10 secs (example only , you can change to how many    seconds you like)
setTimeout(function(){
  populate();
},10000);

数据.php

$sql = 'SELECT id FROM usertbl';
$stmt = $hund->runQuery($sql);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);
echo json_encode($row);
在这一

行中,您忘记关闭<?php...

可能这就是为什么foreach循环无法正常工作的原因

     <?php foreach ($row as $runloop) { ?>
   <table><th> <?php echo $runloop['id']; ?></th></table>
   <?php } ?>

将这些行放在print_r()所在的位置data.php