ajax+php超时操作,延时返回数据

在一次微信扫码登录中,为了减少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检测一次数据,如果有数据就返回。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值