最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AJAX call inside a loop executed before loop ends - Stack Overflow

programmeradmin0浏览0评论

I have the following problem:

I have a loop:

// Code A
. . .
for (var key in dict){
    // Code B
    . . . 
    var list = this.initializeList();
    var selfRef = this;

    jQuery.ajax({
        dataType: 'json',
        url: '/someUrl',
        data: {'sent_data': sendData},
        success: function (recievedData){
            this.function(list);
        }
    });

    // Code C
    . . . 
}
// Code D
. . .

Now, the ideal way for this would be if the order of execution of the code is:

  1. Code A
  2. for loop:
    • Code B
    • AJAX
    • Code C
  3. Code D

But, the problem is in step 2 in the loop: first, Code B is executed, and next - the AJAX call and then again the AJAX code instead of Code C. On the next iteration the AJAX code is executed again instead of Code B. It is really important to me the order of execution to be as presented in the list above. As you can see, the variable list should be re-initialized for each loop, but instead, we have multiple AJAX call with only the first initialization.

How do I fix this?

I have the following problem:

I have a loop:

// Code A
. . .
for (var key in dict){
    // Code B
    . . . 
    var list = this.initializeList();
    var selfRef = this;

    jQuery.ajax({
        dataType: 'json',
        url: '/someUrl',
        data: {'sent_data': sendData},
        success: function (recievedData){
            this.function(list);
        }
    });

    // Code C
    . . . 
}
// Code D
. . .

Now, the ideal way for this would be if the order of execution of the code is:

  1. Code A
  2. for loop:
    • Code B
    • AJAX
    • Code C
  3. Code D

But, the problem is in step 2 in the loop: first, Code B is executed, and next - the AJAX call and then again the AJAX code instead of Code C. On the next iteration the AJAX code is executed again instead of Code B. It is really important to me the order of execution to be as presented in the list above. As you can see, the variable list should be re-initialized for each loop, but instead, we have multiple AJAX call with only the first initialization.

How do I fix this?

Share Improve this question asked May 20, 2013 at 14:01 BelphegorBelphegor 4,76611 gold badges36 silver badges60 bronze badges 7
  • 8 This is bcoz.. Ajax is asynchronous – Adil Shaikh Commented May 20, 2013 at 14:03
  • 4 re-organize it so that instead of looping and sending 30 ajax requests, you're looping and creating 30 pieces of data and sending 1 ajax request. – Kevin B Commented May 20, 2013 at 14:04
  • 1 you need to make your ajax request sequential, like send second request only after first one is pleted – Arun P Johny Commented May 20, 2013 at 14:05
  • 1 You can always use jQuerys $.Deferred. Deferred objects allow you to control the flow. api.jquery./jQuery.Deferred – Jeff Shaver Commented May 20, 2013 at 14:07
  • 1 Also, take a look at $.when api.jquery./jQuery.when – sellmeadog Commented May 20, 2013 at 14:11
 |  Show 2 more ments

2 Answers 2

Reset to default 5

You need to make $.ajax() synchronous (instead of the default asynchronous) like so:

$.ajax({
    ...
    async: false
}); 

This will cause the execution of the script to wait until $.ajax finishes before it continues executing the rest of the script.

I hope this helps!

AJAX (as it's name states it) is asynchronous, which means it is not executed in a specific order. instead, AJAX calls are executed as soon as the server responds to the initial call. What you can do to correct this is add a delay in your function, or add a callback inside the AJAX call so you make sure the code is executed ONLY after the AJAX call has been executed thoroughly

Example of putting Code D in a callback:

// Code A  
...

//run Code D if loop exhausted
var dCheckCount = 0;
function dCheck() { // will be called once for each ajax call
  dCheckCount++;
  if (dCheckCount === dict.length) { // # finished ajax calls = loop size
    // Code D
    ...
  }
}  

for (var key in dict) {  
  // Code B
  ...

  jQuery.ajax({
    dataType: 'json',
    url: '/someUrl',
    data: {'sent_data': sendData},
    success: function (recievedData){
        this.function(list);
        // Code C
        ...

        // check if can run Code D
        dCheck();
    }
  });

}
发布评论

评论列表(0)

  1. 暂无评论