使用ajax获取所有最新数据

时间:2014-09-05 14:24:24

标签: php ajax json while-loop

目前使用ajax时我只返回1个结果,但一旦结果发布,它就不再发布新结果了。

例如:用户在墙上发布了三次,并且没有将这三个新记录插入我的通知中,它打印一个并坐在那里直到用户刷新页面并显示另外两个。如何调整我的代码以返回所有新通知。

此外,如果用户没有通知并且他们得到一个,除非我刷新页面,否则它不显示第一个新通知,除非他们刷新页面..然后这是它开始抓取新数据的时候。

服务器端 - PHP

$json = array();

$com=mysqli_query($mysqli,"SELECT notification_id,notification_content,notification_targetuser,notification_time,notification_triggeredby,notification_throughurl FROM notifications WHERE notification_targetuser='$user2_id' AND notification_id > '$id' AND notification_status=1 ORDER BY notification_id DESC LIMIT 10");
echo mysqli_error($mysqli);

$num = mysqli_num_rows($com);

if($num && $user2_id){

    $json['num'] = $num;
}else{
    $json['num'] = 0;
}
$resultArr = mysqli_fetch_array($com);
$json['notification_id'] = $resultArr['notification_id'];
$json['notification_content'] = $resultArr['notification_content'];
$json['notification_triggeredby'] = $resultArr['notification_triggeredby'];
$json['notification_targetuser'] = $resultArr['notification_targetuser'];
$json['notification_throughurl'] = $resultArr['notification_throughurl'];
$json['notification_time'] = $resultArr['notification_time'];
mysqli_free_result($com);

echo json_encode($json);

}

客户端

$user1_id= mysqli_real_escape_string($mysqli,$_SESSION['id']);
$call="select notification_id,notification_status,notification_targetuser from notifications WHERE notification_status=1 ORDER BY notification_id DESC LIMIT 1";
        $chant=mysqli_query($mysqli,$call) or die(mysqli_error($mysqli));


while($notification=mysqli_fetch_array($chant)){
?>
        <script type="text/javascript">
        var notification_id="<?php echo $notification['notification_id'] ;?>";
        function loadIt() {

    $.ajax({
    type: "GET",
    url: "viewajax.php?notification_id="+notification_id,   
    dataType:"json",
    cache: false,
    success: function(data){
    if(data.num>0){
     $("#notif_actual_text-"+notification_id).prepend('<div class="notif_ui"><div class="notif_text"><img border="1" src="userimages/cropped'+data['notification_triggeredby']+'.jpg" onerror=this.src="userimages/no_profile_img.jpeg" width="40" height="40" ><br /><a href="'+data['notification_throughurl']+'">'+data['notification_content']+' </a><br /><abbr class="timeago" title="'+data['notification_time']+'"> '+data['notification_time']+'</abbr></div></div>');
     i = parseInt($("#mes").text()); $("#mes").text((i+data.num)); 
        }
        if(!data.notification_id.length) {
       //no results...
       return;
    }
    notification_id = data.notification_id; 
    }
    });
    }
    setInterval(loadIt, 10000);              
     </script>

0 个答案:

没有答案