javascript - how to pass to fetch new records only with ajax/json -
i have db containing small news , web app displaying these. update page every 60s jquery.ajax
or jquery.getjson
request .
my question how should pass last id received server next ajax request got newer news? store (on dom, global var, or hidden field, ...)?
yes, need pass argument identifies point search new records. typically handled having server return sequential id or timestamp each ajax response, such subsequent request append argument.
you can store value in various ways, since these typically single-page applications not reloaded, simple javascript variable sufficient. use closures in following example, instead of using global variable:
function fetchdata(last_update_id) { $.ajax({ url: 'fetch_data.php?last_update=' + last_update_id, method: 'get', datatype: 'json', success: function(data) { // last_update_id server response. last_update_id = data.last_update_id; // process ajax response... // relaunch after 60s last_update_id argument. settimeout(function () { fetchdata(last_update_id); }, 60000); } }); }
if go approach, call function 0
or -1
argument, or else long server understand first request. function auto manage itself, keeping last_updated_id
enclosed in closure.
Comments
Post a Comment