0%

ajax轮询,定时去请求服务器数据

服务端

Notify.php

1
2
3
4
5
6
//获取通知消息
public function getNotifyCount()
{
$msg = db('message_logs')->where('isscan',0)->count();
RestfulTools::restData($msg); //这里是封装好的json_encode方法
}

前端

notify.js

1
2
3
<span class="am-icon-envelope-o"></span> 消息 <span class="am-badge am-badge-warning" id="msgCount"> 
{$msgCount} //这是是通过tp的 assign方法分配过来的变量,作为初始值
</span>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script type="text/javascript">

var getting = {
url:"{:url('Notify/getNotifyCount')}",
dataType:'json',
success:function(res) {
console.log(res);
var msgCount = res.result;
$("#msgCount").html(msgCount); //用js的 html方法去改变id为msgCount的值
}
};

//Ajax定时访问服务端,这里是3分钟请求一次。
window.setInterval(function(){
$.ajax(getting)
},180000);

</script>