我正在尝试长轮询并且它与textfile一起使用但我不能让它从表中返回所有内容。
var timestamp = null;
function waitForMsg() {
$.ajax({
type: 'GET',
url: 'update.php?timestamp=' + timestamp,
async: true,
cache: false,
success:function(data) {
// alert(data);
var json = eval('('+data+')');
if (json['msg'] != '') {
$('div.alltext').html(json['msg']); // MD
}
timestamp = json['timestamp'];
setTimeout('waitForMsg()', 1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// alert('error '+textStatus+'('+errorThrown+')');
setTimeout('waitForMsg()', 1000);
}
});
}
update.php
$filename = 'test.txt';
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif = filemtime($filename);
}
// how to rewrite the following?
$response = array();
$response['msg'] = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
如何重写最后一部分以从数据库表中获取所有内容?
编辑:
我尝试了以下但是它只返回一个结果,而不是最新的结果,而是之前的结果。
$response = array();
while($row = mysqli_fetch_assoc($r)) {
$nou = $row['f1'];
$nru = $row['f2'];
$ntext = $row['content'];
$ntime = $row['time'];
}
$response['msg'] = $ntext;
$response['timestamp'] = $currentmodif;
答案 0 :(得分:0)
您正在循环之外分配值,因此您将获得最后的结果。在循环内分配值。
$response = array();
while($row = mysqli_fetch_assoc($r)) {
$nou = $row['f1'];
$nru = $row['f2'];
$response['msg'] = $row['content'];
$response['timestamp'] = $row['time'];
}
echo json_encode($response);
答案 1 :(得分:0)
使用array
将$ntext = $row['content'];
替换为$ntext[] = $row['content'];