Answers:
function doPoll(){
$.post('ajax/test.html', function(data) {
alert(data); // process results here
setTimeout(doPoll,5000);
});
}
这是有关使用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
})
})();
let is_success = false; (function poll() { let timeout = setTimeout(function() { $.ajax({ url: resp.location, type: "GET", success: function(data) { if(YOUR_CONDITION) { is_success=true; } }, dataType: "json", complete: poll, timeout: 2000 }) }, 5000); if(is_success) { console.log("ending poll"); window.clearTimeout(timeout); } })();
从ES6,
var co = require('co');
var $ = require('jQuery');
// because jquery doesn't support Promises/A+ spec
function 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);
jQuery.Deferred()可以简化异步排序和错误处理的管理。
polling_active = true // set false to interrupt polling
function initiate_polling()
{
$.Deferred().resolve() // optional boilerplate providing the initial 'then()'
.then( () => $.Deferred( d=>setTimeout(()=>d.resolve(),5000) ) ) // sleep
.then( () => $.get('/my-api') ) // initiate AJAX
.then( response =>
{
if ( JSON.parse(response).my_result == my_target ) polling_active = false
if ( ...unhappy... ) return $.Deferred().reject("unhappy") // abort
if ( polling_active ) initiate_polling() // iterative recursion
})
.fail( r => { polling_active=false, alert('failed: '+r) } ) // report errors
}
这是一种优雅的方法,但是有一些陷阱...
then()
立即失败,则回调函数应返回另一个thenable对象(可能是another Deferred
),sleep和ajax行都这样做。initiate_polling
运行完成之前。
new Promise( resolve => setTimeout(resolve,1000) ).then( () => alert("done") )
(function poll() {
setTimeout(function() {
//
var search = {}
search["ssn"] = "831-33-6049";
search["first"] = "Harve";
search["last"] = "Veum";
search["gender"] = "M";
search["street"] = "5017 Ottis Tunnel Apt. 176";
search["city"] = "Shamrock";
search["state"] = "OK";
search["zip"] = "74068";
search["lat"] = "35.9124";
search["long"] = "-96.578";
search["city_pop"] = "111";
search["job"] = "Higher education careers adviser";
search["dob"] = "1995-08-14";
search["acct_num"] = "11220423";
search["profile"] = "millenials.json";
search["transnum"] = "9999999";
search["transdate"] = $("#datepicker").val();
search["category"] = $("#category").val();
search["amt"] = $("#amt").val();
search["row_key"] = "831-33-6049_9999999";
$.ajax({
type : "POST",
headers : {
contentType : "application/json"
},
contentType : "application/json",
url : "/stream_more",
data : JSON.stringify(search),
dataType : 'json',
complete : poll,
cache : false,
timeout : 600000,
success : function(data) {
//
//alert('jax')
console.log("SUCCESS : ", data);
//$("#btn-search").prop("disabled", false);
// $('#feedback').html("");
for (var i = 0; i < data.length; i++) {
//
$('#feedback').prepend(
'<tr><td>' + data[i].ssn + '</td><td>'
+ data[i].transdate + '</td><td>'
+ data[i].category + '</td><td>'
+ data[i].amt + '</td><td>'
+ data[i].purch_prob + '</td><td>'
+ data[i].offer + '</td></tr>').html();
}
},
error : function(e) {
//alert("error" + e);
var json = "<h4>Ajax Response</h4><pre>" + e.responseText
+ "</pre>";
$('#feedback').html(json);
console.log("ERROR : ", e);
$("#btn-search").prop("disabled", false);
}
});
}, 3000);
})();
我为此创建了一个小巧的JQuery插件。您可以尝试:
$.poll('http://my/url', 100, (xhr, status, data) => {
return data.hello === 'world';
})
此解决方案:
jQuery的最低版本为1.12
$(document).ready(function () {
function poll () {
$.get({
url: '/api/stream/',
success: function (data) {
console.log(data)
},
timeout: 10000 // == 10 seconds timeout
}).always(function () {
setTimeout(poll, 30000) // == 30 seconds polling period
})
}
// start polling
poll()
})
setTimeout
,有些用过setInterval
。为什么一个人比另一个人偏爱?