首页 > 代码库 > ajax长轮询实现即时聊天室

ajax长轮询实现即时聊天室

前段js:

//处理ajax长轮询
$(function(){
ask_order();
function ask_order(){
var ask_action = "{:U(‘index/order_commet‘,array(‘time‘=>10,‘desk_id‘=>$desk_id))}";
$.ajax({   
                 type:"GET",   
                 dataType:"json",   
                 url:ask_action,   
                 timeout:80000,     //ajax请求超时时间80秒   
                 success:function(data,textStatus){   
                     //从服务器得到数据,显示数据并继续查询   
                     if(data.status=="1"){
//alert(data.data);
var html_str = "";
var result = data.data;
$(result).each(function(i) {
html_str += ‘<li>‘+result[i].goods_name+‘&nbsp;&nbsp;&nbsp;&nbsp;<a data-order="‘+result[i].order_id+‘" data-product="‘+result[i].goods_name+‘" class="little_delete" href="javascript:;">删除</a></li>‘
});
$(‘.product_ordered‘).html(html_str);
                     }   
                  //未从服务器得到数据,继续查询   
                     if(data.status=="0"){   
                          console.log(‘没有数据‘);
                     }   
setTimeout(ask_order, 5000);//5000毫秒,自己定义延迟时间
                 } ,
              //Ajax请求超时,继续查询   
              error:function(){   
                     setTimeout(ask_order, 5000);//5000毫秒,自己定义延迟时间
              }   
                    
             }); 
}
})

 

 

 

 

 

后台PHP:

//处理长轮训方法。
public function order_commet(){
if(empty($_GET[‘time‘])){
die();
}
set_time_limit(0);
$limit_time = $_GET[‘time‘];
$desk_id = $this->desk_id;
$i = 0;
while (TRUE) {
usleep(500000);
$i++;
$result = $this->order_mod->get_order_by_desk($desk_id);
if($result[‘result‘] == 1){
$this->ajaxReturn(array(‘status‘=>1,‘data‘=>$result[‘data‘]));
die();
}
if($i == $limit_time || !$desk_id){
$this->ajaxReturn(array(‘status‘=>0,‘data‘=>‘无数据‘));
die();
}
}
}