开发者

how to pass to fetch new records only with ajax/json

开发者 https://www.devze.com 2023-01-18 12:45 出处:网络
I have a DB containing small news and a web开发者_JAVA百科 app displaying these. I would like to update my page every 60s with a jquery.ajax or jquery.getJSON request .

I have a DB containing small news and a web开发者_JAVA百科 app displaying these. I would like to update my page every 60s with a jquery.ajax or jquery.getJSON request .

My question is how should I pass the last id i received from the server to the next ajax request so that i got only newer news? Where do I store it (on the DOM, into a global var, or hidden field, ...)?


Yes, you need to pass some argument that identifies the point from where to search for new records. This is typically handled by having the server return a sequential id or a timestamp with each Ajax response, such that the subsequent request will append this as an argument.

You can store this value in various ways, but since these are typically single-page applications which are not reloaded, a simple JavaScript variable is often sufficient. You could also use closures as in the following example, instead of using a global variable:

function fetchData(last_update_id) {
   $.ajax({
      url:      'fetch_data.php?last_update=' + last_update_id,
      method:   'GET',
      dataType: 'json',
      success:  function(data) {
         // Get the last_update_id from the server response.
         last_update_id = data.last_update_id;

         // Process your Ajax response...

         // Relaunch after 60s with the last_update_id argument.
         setTimeout(function () {
           fetchData(last_update_id);
         }, 60000);
      }
   });
}

If you go for this approach, you would initially call this function with a 0 or a -1 argument, or anything else as long as the server will understand that it is the first request. Then the function will auto manage itself, keeping the last_updated_id enclosed in a closure.

0

精彩评论

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

关注公众号