The function to be implemented here is: log in to the website by scanning the QR code of the WeChat official account with parameters. But it is obvious that if ajax requests the server continuously, this will increase the load on the server. Therefore, this example uses js's setInterval to periodically call and execute an ajax function to request data from the server, but the request is successful or the request is made a certain number of times. If it still fails, use the clearinterval function to clear the timer.
The code and comments are as follows: (The backend is implemented using thinkPHP, so the js code contains some thinkPHP syntax rules)
<script type="text/javascript" src="__CSS__/bootstrap-3.3.5-dist/js/bootstrap.min.js"></script> <script type="text/javascript"> var uid = "{$uid}"; var i = 0; var timer; $().ready(function(){ //打开扫码登录模态框 $('#login').click(function(){ //如果用户已经登录,则返回 if(uid){ return ; } //打开模态框,通过remote选项从远程加载数据 $('#loginModel').modal({ remote: "{:U('user/login')}" }); }); //模态框隐藏之后清空数据 $("#loginModel").on("hidden.bs.modal", function() { $(this).removeData("bs.modal"); }); //当模态框显示出来后,通过定时返回来向服务器请求数据,定时器是每三秒请求一次服务器 $('#loginModel').on('shown.bs.modal', function (e) { timer = setInterval(ajax_request, 3000); }); }); //ajax 请求函数, function ajax_request(){ i++; //如果已经请求20此没有请求成功,则强制结束,给出提示信息,因为每3s调用一次,供调用20次,大概就是一分钟的时间 if(i > 20){ $('.login_info1').html('<span style="color:red;">登录超时,如需登录请刷新页面~</span>'); clearInterval(timer); return ; } $.ajax({ type: "post", url: "{:U('User/login_qrcode')}", timeout : 3000, data: { "scene_id": $('#scene_id').val() }, success: function (msg){ if(1 == msg.status){ $('.login_info1').html('<span style="color:#0C9;">'+msg.info+'</span>'); setTimeout(refresh, 3000); return ; } }, error: function(){ } }); } //重载页面 function refresh(){ location.reload(); } </script>
Related recommendations:
PHP implements WeChat PC QR code login
How to use QR code login? Summarize the usage of QR code login examples
Detailed explanation of the principle of QR code login
The above is the detailed content of Ajax polling request status. For more information, please follow other related articles on the PHP Chinese website!