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);
}
}