ajax 轮询 和 php长连接

 只看加粗的字体

js   部分

      1:  ajax 成功回调函数中 一定要用时间函数间隔调用  get_comment().

get_comments('init');
function get_comments(msg){
if(msg == undefined){
msg = '';
}
var post_id ="{$id}";
$.ajax({
type: "GET",
url: "",
data: {},
dataType: "json",
success: function(data){
// 这里 你自己处理 自己的data.
setTimeout("get_comments()",60000);
}
})

}

php部分

      1:   根据条件,取得数据的条数,取名 old_counts

      2:  根据 while(true)循环,再次查询数据库的条数,new_counts;

      3: 新的条数和旧地条数做比较。比较结果不一样,返回结果。

      4:  break ,跳出循环

      5 : $time_count 是  对于一定的时间内,数据没有更新,也跳出循环。

public  function get_comment(){
$post_id = I('get.post_id',0,'intval');
$table = I('get.table');
$msg = I('get.msg');
$comment_model=D("Common/Comments");
$comments=$comment_model->where(array("post_table"=>$table,"post_id"=>$post_id,"status"=>1,'user_type'=>2))->order("createtime ASC")->select();

$OldCommentData = count($comments);

if($msg=='init'){
if(!empty($comments)){

$comments =self::forData($comments);
}
echo json_encode($comments);exit;
}
$time_count =0;
while(true){
set_time_limit(0);// 函数允许脚本运行的时间。设为0,程序不受限制。
$time_count++;
$newComments=$comment_model->where(array("post_table"=>$table,"post_id"=>$post_id,"status"=>1,'user_type'=>2))->order("createtime ASC")->select();

$newCommentData = count($newComments);
if($newCommentData != $OldCommentData){
if(!empty($comments)){
$newComments =self::forData($newComments);
echo json_encode($newComments);
break;
}
}
usleep(1000);
//一定的时间后没有数据变化也跳出
if($time_count >= 800){
$data = "";
echo json_encode($data);
break;
}
}

}

转载于:https://www.cnblogs.com/fengshu/p/7080758.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值