开发者

CouchDB - Continuous feed using jQuery

After reading a similar questions here, I'm curious as to whether this is at all possible?

I understand I can make the below work, by wrapping in a setInterval function, which repeatedly calls the check-for-changes function, but I would much rather use continuous polling.

The database regularly gets updated every minute during peak times, but seems a waste to keep polling the database during off-peak times...

$.getJSON('http://localhost:5984/db?callback=?', function(db) {
    console.l开发者_如何学Goog(db.update_seq);
    $.getJSON('http://localhost:5984/db/_changes?since='+db.update_seq+'&feed=continuous&callback=?', function(changes) {
        console.log(changes);
    });
}); 

Firebug shows when a change is indeed made, something happens, but only null is returned.

I'm also on the same domain, calling a page from localhost/index.php


Rather than using continuous or long-polling, you could instead adopt an adaptive strategy. Perhaps start at 1 minute intervals. If there are no updates, up it to 2 minutes, then 3, 4, 5 etc. If there are some updates then the interval can be modified to reflect the time until the next expected update.

Basically it all boils down to how important it is to you to actually get the notifications of updates in near-real-time and how large a delay you are willing to deal with.


Here's a concrete example of Colin Ross's accepted answer:

(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));

This example source code came from this now archived blog: https://web.archive.org/web/20170821130003/http://schinckel.net/2012/01/22/jquery-long-poll-for-couchdb-changes./

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜