开发者

Read continuous feed from CouchDB using Ajax/jQuery

I want to listen for continuous changes from CouchDB using jQuery - now this works:

http://localhost:5984/testdb/_changes?feed=continuous

which means that I get a new line of json every time there is a db update - but how do I read updates off this URL using jQuery?

I tried using this but it doesn't work:

$.ajax(
{
  url : "http://localhost:5984/testdb/_changes?feed=continuous&callback=?",
  dataType : 'json',
  success : function(data)
  {
    alert(data.results.length);
  }
});

Edit: $.ajax calls the "success" function and returns immediately, it doesn't "poll" for changes.. (timeline column for ajax column in image below is 16ms)

Read continuous feed from CouchDB using Ajax/jQuery

And no, it isn't a cross-domain ajax problem - I can see in fireBug there is a response with the right number of elements

So any guidance/advice would be appreciated - it doesn't have to be jQuery - plain old javscri开发者_如何学Gopt would do as well


Off the top of my head, I can think of two good ways to do this.

  1. Using a timer (ie., setTimeout();), run the AJAX call on the changes feed every X seconds. You will also store the last sequence number that you received, so that you can tell the changes feed which sequence number to start at the next time you poll. This will prevent duplicate data and make the responses smaller.

  2. Depending on what browsers you need to support, you might be able to use the EventSource API. Here is a jQuery implementation: https://github.com/rwldrn/jquery.eventsource


As Gjorgji Tashkovski mentioned feed=continuous is intended for server-side, you can use feed=longpoll for your use case.

(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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜