消息系统设计Part1

像交友网那样,只要有人看了你的个人资料,就一个窗口实时提醒你, 效果的确不错,最近公司要做类似的功能, 本人先从前端入手,用AJAX轮循的方式去请求服务器,后来发现开N个页面,服务端就有N个请求,后来考虑先在客户端储存第一次从服务器发出请求前的时间,和最后一次从服务器请求返回后的时间,通过时间来判断是否要发出AJAX请求到服务器,

    客户端储存数据有三种方式 cookies,user-data,sessionStorage     如果要用后两者建议去看看http://www.jstorage.info/  专门有人写好的JS,支持性不错。

大家可以去查查资料,看看这几种的区别 

    本人采人第一种  cookies来储存

View Code

 
$(document).ready(function () {
    GetData();

});
function GetData() {
    var time = $.cookie("lsg");
    if (time == null) {
        time = new Date();
        $.cookie("lsg", time, { path: "/" });
    }
    var difference = (new Date()).getTime() - (new Date(Date.parse(time))).getTime();
    var thisSecond = Math.floor(difference / (1000)); //获取秒
    var requestTime = 60;//请求时间间隔 单位秒
    if (thisSecond > requestTime) {
        time = new Date();
        $.cookie("lsg", time, { path: "/" });//请求前
        console.log('从服务器取一次数据' + time.toString());
        time = new Date();
        $.cookie("lsg", time, { path: "/" }); //请求后
        setTimeout(GetData, requestTime * 1000);
    }
    else {
        setTimeout(GetData, 1000);
    }
    

  

 View Code

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
    <script src="jquery.cookie.js" type="text/javascript"></script>
    <script type="text/javascript" src="Singleton.js"></script>
</head>
<body>

</body>
</html

      这样就能确保所有引用页在规定的时间内,对服务器请求一次。有什么不足的地方还求大家指正

原文地址:https://www.cnblogs.com/shenggen/p/2391881.html