<!DOCTYPE html>
<html>
<head>
<meta charset=
"UTF-8"
>
<title>ajax长轮询和短轮询</title>
</head>
<script type=
"text/javascript"
src=
"js/jquery-3.3.1.min.js"
></script>
<script type=
"text/javascript"
>
function
shortPolling() {
setInterval(shortAjax,5000);
}
function
shortAjax() {
$.ajax({
type:
"get"
,
url:
"/javatest/student/findOneShort/"
+ 10001,
dataType:
"json"
,
success:
function
(result) {
var
msg = $(
"#message"
).html() + result.id+
':'
+result.name+
'='
+result.score+
'\n'
;
$(
"#message"
).html(msg);
},
timeout:10000,
error:
function
(error) {
console.log(
"ajax执行失败"
);
}
})
}
function
longPolling() {
$.ajax({
type:
"get"
,
url:
"/javatest/student/findOneLong/"
+ 10001,
dataType:
"json"
,
success:
function
(result) {
var
msg = $(
"#message"
).html() + result.id+
':'
+result.name+
'='
+result.score+
'\n'
;
$(
"#message"
).html(msg);
longPolling();
},
timeout:15000,
error:
function
(error) {
console.log(
"ajax执行失败"
);
longPolling();
}
})
}
</script>
<body>
<p>【操作】:<div><input type=
"button"
id=
"short"
onclick=
"shortPolling()"
value=
"ajax短轮询"
/><br/>
<p>【操作】:<div><input type=
"button"
id=
"long"
onclick=
"longPolling()"
value=
"ajax长轮询"
/><br/>
<p>【接收内容】:<div><textarea id=
"message"
rows=
"10"
cols=
"30"
></textarea></div>
</body>
</html>