ajax轮询——模拟动态监视来访信息

本文介绍了一种使用HTML、JavaScript和Java技术实现的访客监测系统。该系统通过前端页面上的按钮启动定时任务,每隔一段时间通过Ajax请求从服务器获取访客信息,并更新到页面上。如果监测到来访者,则会显示其基本信息。

html

<input id="msg" readonly="true"/>
<button onclick="onSutib()">开始监视来访者</button>

js

<script type="text/javascript">
    function onSutib(){
        c = window.setInterval("getResult('http://localhost:8080/ModelTest1/test/getUser')",1000); //间隔多少秒去触发ajax
    }
    function getResult(url){
        $.ajax({
            type:'get',
            url:url,
            dataType:'json',
            async: true,
            success:function(json){
                i++; //记录轮询的次数
                if(json.type == 1){
                    $("#msg").val("来访者:姓名:"+json.name+"性别:"+json.sex);
                    alert("来访者:姓名:"+json.name+"性别:"+json.sex)
                    //关闭轮询
                    //window.clearInterval(c);
                }else{
                    $("#msg").val("暂无来访");
                }
            }
        });
    }
</script>

java 

@Controller
@RequestMapping("/test")
public class Test {

    static int num = 0;

    @ResponseBody
    @RequestMapping(value = "getUser", method = RequestMethod.GET)
    public String getUser() throws IOException {
        Map map = new HashMap();
        //通过条件模拟有来访用户
        if (num == 50 || num == 100) {
            map.put("type", 1);
            map.put("name", "韦小宝" + num);
            map.put("sex", "男");
        } else {
            map.put("type", 0);
        }
        num++;
        return JSON.toJSONString(map);
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值