这是一篇关于使用jQuery 进行长轮询(长期持有的HTTP请求)的有用文章。源自本文的代码段:(function poll() {
setTimeout(function() {
$.ajax({
url: "/server/api/function",
type: "GET",
success: function(data) {
console.log("polling");
},
dataType: "json",
complete: poll,
timeout: 2000
})
}, 5000);})();
这将仅在ajax请求完成后才生成下一个请求。
上述内容的变体,将在第一次调用等待/超时间隔之前立即执行。(function poll() {
$.ajax({
url: "/server/api/function",
type: "GET",
success: function(data) {
console.log("polling");
},
dataType: "json",
complete: setTimeout(function() {poll()}, 5000),
timeout: 2000
})})();