我在获取最新的数据时遇到了一点麻烦。所有我想要的是找到是否有任何新的数据在数据库和打印记录的数量回到我的页面。我有ajax工作,它有最后的notification_id,它发送到php。我只需要让php选择任何新数据,将其发送回来并打印出来。
我还没有尝试过轮询,但是当我有这个工作并更好地理解它时,我会研究它。
<? $call="SELECT * FROM notifications WHERE notification_targetuser='$user1_id' AND notification_status=1 ORDER BY notification_id DESC LIMIT 1";
$chant=mysqli_query($mysqli,$call) or die(mysqli_error($mysqli));
while($notification_id=mysqli_fetch_array($chant))
{
?>
<script type="text/javascript">
setInterval(function(){
var notification_id="<?php echo $notification_id['notification_id'] ;?>"
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id,
dataType:"json",
cache: false,
success: function(data){
$(".mess"+notification_id).prepend("<span class'mess' id='mes'>"+response['notification_id']+"</span>");
}
});
},20000);
</script>
<? }?>
回声";
PHP viewajax.php -将其更改为JSON -但在响应
中获得{"notification_id":null} <?php
session_start();
include"database.php";
if(isset($_GET['notification_id']))
{
$id=$_GET['notification_id'];
$user1_id=$_SESSION['id'];
$json = array();
$com=mysqli_query($mysqli,"select notification_id from notifications where notification_id>'$id' AND notification_targetuser='$user1_id' AND notification_status=1");
$resultArr = mysqli_fetch_array($com);
$json['notification_id'] = $resultArr['notification_id'];
mysqli_free_result($com);
echo json_encode($json);
}?>
如果你想要新的数据,为什么不直接做notification_id > '$id'
而不是notification_id='$id'
呢?
我假设notification_id
是一个整数索引列,$id
是前端接收到的最后一个id。