javascript - Ajax Inside For Loop -
in chrome extension writing need validate objects have stored in localstorage against server . created loop sends data each localstorage element , needs response . code this:
(var key in localstorage) { if (! condition ) continue; var httprequest = new xmlhttprequest(); httprequest.onreadystatechange = function() { if (httprequest.readystate === 4 && httprequest.response == 200) { 'key' loop } } }; var url = base_path ; httprequest.open("post", url); httprequest.send(some data); }
however while debugging seems in ajax response , 'key' loop isn't key need : expecting same key loop matches each ajax call , got same key ajax calls . doing wrong or expecting isn't possible ? thought since ajax inside closure function , values kept in memory or of sort .
extract actual ajax call separate function:
function ajaxcall( key ) { var httprequest = new xmlhttprequest(); httprequest.onreadystatechange = function() { if ((httprequest.readystate === 4) && (httprequest.response == 200)) { 'key' loop } }; var url = base_path ; httprequest.open("post", url); httprequest.send(some data); } (var key in localstorage) { if ( condition ) { ajaxcall( key ); } }
reason is, creating closure function passed onreadystatechange
. functions point same key
variable, holds 1 (the last) value ajax calls, after loop finished.
when create separate function (like ajaxcall()
in example), create different context each call , hence callbacks point different keys.
Comments
Post a Comment