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;
}
}
}