jQuery,简单的轮询示例我正在学习jQuery,我正在尝试找到一个简单的代码示例,它将针对某个条件轮询API。(即每隔几秒请求一个网页并处理结果)我熟悉如何在jQuery中使用AJAX,我似乎无法找到让它在“计时器”上执行的“正确”方式。
4 回答
喵喵时光机
TA贡献1846条经验 获得超7个赞
function doPoll(){
$.post('ajax/test.html', function(data) {
alert(data); // process results here
setTimeout(doPoll,5000);
});}
慕妹3146593
TA贡献1820条经验 获得超9个赞
代码片段:
(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
})})();
catspeake
TA贡献1111条经验 获得超0个赞
来自ES6,
var co = require('co');var $ = require('jQuery');// because jquery doesn't support Promises/A+ specfunction ajax(opts) {
return new Promise(function(resolve, reject) {
$.extend(opts, {
success: resolve,
error: reject });
$.ajax(opts);
}}var poll = function() {
co(function *() {
return yield ajax({
url: '/my-api',
type: 'json',
method: 'post'
});
}).then(function(response) {
console.log(response);
}).catch(function(err) {
console.log(err);
});};setInterval(poll, 5000);不使用递归(函数堆栈不受影响)。
在setTimeout-recursion需要尾调用优化的情况下不会受到影响。
慕尼黑的夜晚无繁华
TA贡献1864条经验 获得超6个赞
function poll(){
$("ajax.php", function(data){
//do stuff
}); }setInterval(function(){ poll(); }, 5000);- 4 回答
- 0 关注
- 1269 浏览
添加回答
举报
0/150
提交
取消
