Ajax Polling request status is very important in Ajax learning is also necessary to grasp the knowledge point, today and everyone to share this part of the content, together to see it.
the function to be implemented here is to log in to the website by scanning the QR code of the public number with parameters.
but obviously, if Ajax continuously requests the server, this will aggravate the load of the server, so this example uses the JS setinterval to periodically invoke the execution of an AJAX function to request data from the server. However, the timer is emptied with the Clearinterval function after a successful request or a certain number of requests.
The code and comments are as follows: (the backend is implemented with 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 () {
//Open scan login modal box
$ (' #login '). Click (function () {
//If the user is already logged in, return
if (UID) {
return;
}
//Open modal box to load data remotely from remote option
$ (' #loginModel '). Modal ({
Remote: "{: U (' User/login ')}"
});
});
//After the modal box is hidden, empty the data
$ ("#loginModel"). On ("Hidden.bs.modal", function () {
$ (this). Removedata ("Bs.modal");
});
//When the modal box is displayed, request data to the server by a timed return, the timer is to request the server every three seconds
$ (' #loginModel '). On (' Shown.bs.modal ', function (e) {
timer = setinterval (ajax_request, +);
});
});
//ajax request function,
function Ajax_request () {
i++;
//If you have requested 20 this no request succeeds, then force the end, give the prompt information, because every 3s call once, for call 20 times, about a minute of time
if (i >) {
$ ('. Login_info1 '). html (' <span style= "color:red;" > Login timeout, if you need to log in please refresh Page ~</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, +);
return;
}
},
error:function () {
}
});
}
//Reload page
function Refresh () {
location.reload ();
}
</script>
article source: unix8
Ajax polling request for source code sharing