在一次微信扫码登录中,为了减少ajax的请求次数研究了一下,ajax中的timeout的应用,
js代码如下:
var dataarr = {
type: "POST",
url: "__MODULE__/System/CheckUserWx",
timeout:65000, //ajax请求超时时间65秒
data:{uid:'<{$uid}>',rand:'<{$rand}>'},//60秒后无论结果服务器都返回数据
success:function(res) {
if(res.bool){
$('#info').html('<i class="Hui-iconfont c-success f-20"></i> 绑定成功!');
var t= setTimeout('layer_close()',1000);
}else{
$.ajax(dataarr);
}
},
// Ajax请求超时,继续查询
error: function(XMLHttpRequest, textStatus, errorThrown) {
if (textStatus == "timeout") {
$.ajax(dataarr);// Ajax请求超时,继续查询
}
}
};
$.ajax(dataarr);
PHP端的代码:
//检测微信绑定情况
public function CheckUserWx(){
$res['bool'] = false;
if(IS_POST){
$rand = I('post.rand');
$uid = I('post.uid');
$i = 0;
while(true){
usleep(500000);//暂停5s
$i++;
//获取数据
$rand = M('WechatRand')->where(array('rand'=>$rand))->find();
if($rand['openid']){
$arr['uid'] = $uid;
$arr['openid'] = $rand['openid'];
$b = M('users')->save($arr);
if($b !== false){//有值就返回数据
M('WechatRand')->delete($rand['id']);
$res['bool'] = true;
$user = M('users')->find($uid);
$this->action('绑定微信!');
$wx = new \Wechat\Controller\SendMsgController();
$wx->BD_user_wx($rand['openid'],$user['username']);
$this-> ajaxReturn($res,'JSON');
break;
}
}
if($i > 20){//检测超过20次返回错误
$res['bool'] = false;
$this->ajaxReturn($res,"JSON");
break;
}
}
}
}
服务端每5s检测一次数据,如果有数据就返回。