javascript - Making an ajax request multiple times -


i have 3 "sources," each of needs have ajax call made. however, because ajax asynchronous, can't put in loop. @ same time, can't async: false because it's bad have browser hang.

thus, decided have ajax called multiple times in it's success callback, , construct kind of artificial loop. problem is, it's not working (i'll explain error later on in question). here's relevant code.

    counter: 0,     load: function(source, start_month, end_month, start_year, end_year) {       start_month = parseint(start_month) + 1;       end_month = parseint(end_month) + 1;        var parsedate = d3.time.format("%y-%m-%d").parse;        if(source == 0) {         $.ajax({           datatype: "json",           url: ...           data: {               ...           },           crossdomain: true,           success: function(raw_data) {             posts.counter++;             if(posts.counter < 4) {               alert(posts.counter);               posts.load(source, start_month, end_month, start_year, end_year);             } else {               alert("plot graph");             }           }         });       } ... 

this entire code block exists inside posts closure. couple of questions:

  1. is style? there more efficient way go doing this?

  2. for reason alert firing twice... shouldn't firing 3 times 1, 2, , 3?

i suggest using js promises (aka deferred objects). jquery's when , functions (http://api.jquery.com/jquery.when/ , http://api.jquery.com/deferred.then/). can use deferred objects make 3 asynchronous calls , wait process data until 3 calls return.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -