简体   繁体   中英

How to know when all the ajax calls in JQuery each loop are completed?

I am having an each loop in JQuery in which I trigger an ajax request. I want to display one success message after all the ajax calls are done executing.

My code goes below,

$('.container input:checked').each(function() {
  json_data = $(this).parent().parent().find('.case_json').html()
  $.ajax({
    type: "POST",
    url: "/some_action",
    data: { json_data : json_data },
    success: function(data) {
      console.log('saved')
    }
  })
}).promise().done( function(){ $('#import_message').show().addClass('alert alert-success').html('Data imported successfully!') } );

But the problem with the code is my success message is getting displayed way before the ajax calls are done executing.

What am I doing wrong? Or do I need to change the way I implemented?

I think you want to build an array of promises then use $.when.apply. There is a similar problem here: What is cleanest way to turn Array of JQuery Promises into a JQuery Promise of an Array? .

You need to combine usage $.map function with $.when, here is how it should look like:

$.when.apply($, $('.container input:checked').map(function() {
  json_data = $(this).parent().parent().find('.case_json').html()
  return $.ajax({
    type: "POST",
    url: "/some_action",
    data: { json_data : json_data },
    success: function(data) {
      console.log('saved')
    }
  })
}))
.done( function(){ 
    $('#import_message').show().addClass('alert alert-success').html('Data imported successfully!') 
} );

Map function would create an array of deffereds, this array is passsed to $.when function, the problem is that it's doesn't support array as argument, but support any number of parameters, so we can use .apply() which take array of promises and pass to function as arguments.

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