Read continuous feed from CouchDB using Ajax/jQuery

旧巷老猫 提交于 2020-01-13 02:10:22

问题


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)

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 javscript would do as well


回答1:


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



来源:https://stackoverflow.com/questions/4232391/read-continuous-feed-from-couchdb-using-ajax-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!