以后台系统消息提醒为例,实现效果为实时的提示条数更新显示:
html及样式:
1234
#red {
min-width: 2rem;
height: 2rem;
border-radius: 50%;
background-color: red;
font-size: 0.12rem;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
font-style: normal;
position: absolute;
top: 0.5rem;
right: 0.5rem;
}
页面端 ,使用ajax轮询。setInterval("getCount()",500);
function getCount(){
$.ajax({
type : "POST",
async:true,
url : ctx + "business/message/count",
success : function(data) {
$('#red').html(data.number);
},
error: function(){
//请求出错处理
alert("Error!");
}
});
}
setInterval是按照固定的时间周期(单位是毫秒)去执行一个函数或者计算表达式。同时在Ajax请求里有一个参数非常重要,async为True时代表了是异步请求,这样不会锁死浏览器,但是如果为False时代表了同步请求就会锁住浏览器。
后台类:@PostMapping("/count")
@ResponseBody
public Message getCount()
{
// 取身份信息
Message message = messageService.selectCount(ShiroUtils.getLoginName());
return message;
}
轮询(Polling)是一种CPU决策如何提供周边设备服务的方式,又称“程控输出入”(Programmed I/O)。轮询法的概念是,由CPU定时发出询问,依序询问每一个周边设备是否需要其服务,有即给予服务,服务结束后再问下一个周边,接着不断周而复始。
在WEB上来说就是客户端一直向服务端发起请求,服务端返回数据,不论返回什么都会再次向服务端发送请求。
本文出自http://swzhinan.com/
本文由站长原创或收集,不代表本站立场,如若转载,请注明出处:http://www.swzhinan.com/post/282.html