简体   繁体   中英

Making an ajax request multiple times

I have three "sources," each of which needs to have an ajax call made. However, because Ajax is asynchronous, I can't just put it in a for loop. At the same time, I can't do async: false because it's bad to have the browser hang.

Thus, I decided to have the Ajax be called multiple times in it's success callback, and construct a kind of artificial loop. Problem is, it's not working properly (I'll explain the error later on in the question). Here's my 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 a posts closure. Just a couple of questions:

  1. Is this good style? Is there a more efficient way to go about doing this?

  2. For some reason the alert is only firing twice... shouldn't it be firing 3 times with 1, 2, and 3?

I suggest using JS promises (aka deferred objects). Look into jQuery's when and then functions ( http://api.jquery.com/jquery.when/ and http://api.jquery.com/deferred.then/ ). You can use deferred objects to make 3 asynchronous calls and wait to process the data until all 3 calls return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM