有時(shí)候,需要服務(wù)器主動(dòng)給瀏覽器推送數(shù)據(jù),這里用ajax來實(shí)現(xiàn)這種功能,具體請(qǐng)看這里:
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(){
//打開掃碼登錄模態(tài)框
$('#login').click(function(){
//如果用戶已經(jīng)登錄,則返回
if(uid){
return ;
}
//打開模態(tài)框,通過remote選項(xiàng)從遠(yuǎn)程加載數(shù)據(jù)
$('#loginModel').modal({
remote: "{:U('user/login')}"
});
});
//模態(tài)框隱藏之后清空數(shù)據(jù)
$("#loginModel").on("hidden.bs.modal", function() {
$(this).removeData("bs.modal");
});
//當(dāng)模態(tài)框顯示出來后,通過定時(shí)返回來向服務(wù)器請(qǐng)求數(shù)據(jù),定時(shí)器是每三秒請(qǐng)求一次服務(wù)器
$('#loginModel').on('shown.bs.modal', function (e) {
timer = setInterval(ajax_request, 3000);
});
});
//ajax 請(qǐng)求函數(shù),
function ajax_request(){
i++;
//如果已經(jīng)請(qǐng)求20此沒有請(qǐng)求成功,則強(qiáng)制結(jié)束,給出提示信息,因?yàn)槊?s調(diào)用一次,供調(diào)用20次,大概就是一分鐘的時(shí)間
if(i > 20){
$('.login_info1').html('span style="color:red;">登錄超時(shí),如需登錄請(qǐng)刷新頁面~/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>