Thursday, 15 January 2015

jquery - Javascript AJAX Response, for loop difficulty -



jquery - Javascript AJAX Response, for loop difficulty -

this question has reply here:

how homecoming response asynchronous call? 11 answers

i have little problem. namely, value of variable: count_green outside of loop. has thought how can that? here snippet of code:

function state(type, count, list_name){ var count_green = 0; var count_yellow = 0; var count_red = 0; (i = 0; < count; i++){ var jqxhr = $.ajax( "/custom_data/getstate/" + type[i]).done(function(result) { (j = 0; j < count; j++){ if(result.type == type[j]){ if(result.value == "green"){ $("#" + type[j]).css("color","#468847"); count_green = count_green + 1; } if(result.value == "yellow"){ $("#" + type[j]).css("color","#f89406"); count_yellow = count_yellow + 1; } if(result.value == "red"){ $("#" + type[j]).css("color","#b94a48"); count_red = count_red + 1; } } } }); } //here need value of count_green, count_yellow , count_green //unfortunately outside of loop 0. addcounters(count_green, count_yellow, count_red); } function addcounters(state_green, state_yellow, state_red){ $(".line").find(".list").append('<span class="badge pull-left count_badge badge-success">' + state_green + '</span>'); }

as can see if set method call: addcounters in loop many badges why need access count-variables: count_green, count_yellow , count_red outside of loop , ajax code. saw solutions callback need 1 time value of variables, if work callback more 1 time values.

thank in advance.

one solution synchronous requests. http://api.jquery.com/jquery.ajax/ @ async property.

$.ajax( "/custom_data/getstate/" + type[i], {async: false}).done(...)

another solution this

var requestcount = 0; (i = 0; < count; i++){ var jqxhr = $.ajax( "/custom_data/getstate/" + type[i]).done(function(result) { (j = 0; j < count; j++){ if(result.type == type[j]){ if(result.value == "green"){ $("#" + type[j]).css("color","#468847"); count_green = count_green + 1; } if(result.value == "yellow"){ $("#" + type[j]).css("color","#f89406"); count_yellow = count_yellow + 1; } if(result.value == "red"){ $("#" + type[j]).css("color","#b94a48"); count_red = count_red + 1; } } } requestfinished(count_green, count_yellow, count_red); }); } function requestfinished(count_green, count_yellow, count_red){ requestcount++; if(requestcount == count){//all requests finished addcounters(count_green, count_yellow, count_red); } }

javascript jquery ajax

No comments:

Post a Comment