javascript - Ajax calls inside loop need sequential responses -
i need make 3 or less ajax calls, , responses need appended dom in same order requested.
i have following function, problem responses not in correct order when appended dom.
i wouldn't want use async: false property because blocks ui , it's performance hit of course.
mod.getarticles = function( ){ //mod.vars.ajaxcount start @ 0-2 for( var = mod.vars.ajaxcount; < 3; i++ ){ //mod.vars.pushids array ids ajaxed in var id = mod.vars.pushids[i]; $.ajax({ url: '/ajax/article/' + id + '/', type: "get", datatype: 'html', error: function() { console.error('get article ajax error'); } }).done( function( data ) { if (data.length) { mod.appendarticle( data ); } else { console.error('get article ajax output error'); } }); } };
you need append article position, based on example i
variable have. or wait of requests , append them in order. this:
mod.getarticles = function( ){ var load = function( id ) { return $.ajax({ url: '/ajax/article/' + id + '/', type: "get", datatype: 'html', error: function() { console.error('get article ajax error'); }); }; var ondone = function( data ) { if (data.length) { mod.appendarticle( data ); } else { console.error('get article ajax output error'); } }; var requests = []; for( var = mod.vars.ajaxcount; < 3; i++ ){ requests.push(load(mod.vars.pushids[i])); } $.when.apply(this, requests).done(function() { var results = requests.length > 1 ? arguments : [arguments]; for( var = 0; < results.length; i++ ){ ondone(results[i][0]); } }); };
Comments
Post a Comment