我有这个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);
index.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);
data.php
$sql = 'SELECT id FROM usertbl';
$stmt = $hund->runQuery($sql);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);
echo json_encode($row);
关于javascript - 表中自动刷新的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38259612/