在阅读了类似的问题here后,我很好奇这是否可能?
我理解我可以通过包装setInterval函数来完成下面的工作,该函数重复调用check-for-changes函数,但我宁愿使用连续轮询。
数据库会在高峰期间每分钟定期更新,但在非高峰时段继续轮询数据库似乎是浪费......
$.getJSON('http://localhost:5984/db?callback=?', function(db) {
console.log(db.update_seq);
$.getJSON('http://localhost:5984/db/_changes?since='+db.update_seq+'&feed=continuous&callback=?', function(changes) {
console.log(changes);
});
});
Firebug显示确实发生了更改时,会发生某种情况,但只返回null。
我也在同一个域上,从localhost / index.php调用一个页面
答案 0 :(得分:2)
您可以采用自适应策略,而不是使用连续或长轮询。也许每隔1分钟开始一次。如果没有更新,则将其更新为2分钟,然后是3,4,5等。如果有更新,则可以修改间隔以反映下一次预期更新之前的时间。
基本上,这一切都归结为实际获得近实时更新通知以及您愿意处理多大延迟的重要性。
答案 1 :(得分:0)
以下是 Colin Ross 接受的答案的具体示例:
(function($) {
// this is a recursive function
function longpoll(database, last_seq) {
var url = "/" + database + "/_changes?feed=longpoll";
// If we don't have a sequence number, then see where we are up to.
if (last_seq) {
url = url + "&since=" + last_seq;
}
$.ajax({
type: "GET",
url: url,
dataType: 'json',
success: function(data) {
// Now we need to see what to do with the data.
console.log(document.data.results);
// And set up the re-run of the fetch query.
// recursive call
longpoll(database, data.last_seq);
}
})
}
$.couch.longpoll = longpoll;
}(jQuery));
这个示例源代码来自这个现已归档的博客: https://web.archive.org/web/20170821130003/http://schinckel.net/2012/01/22/jquery-long-poll-for-couchdb-changes./