jQuery AJAX solution inside each() loop

后端 未结 3 1839
暖寄归人
暖寄归人 2020-12-07 06:41

I have noticed that I\'m having problems when I\'m using AJAX in jQuery inside a .each() loop. Only the first record in my database are being updated when the script execute

3条回答
  •  臣服心动
    2020-12-07 07:02

    Your issue is in this block of code:

    request.done(function(){
        document.location.reload();
    });
    

    Since the actions are asynchronous, this line is being executed before the save is completing, thus after the first save does complete, it executes the done logic.

    You need to create an array of deferred objects that you can then wait until they are all executed before proceeding forward with your logic using the jQuery .when()/.then() functions.

    Here is a previous StackOverflow question that details how to setup this situation. Please read the accepted answer of jQuery when each is completede trigger function.

提交回复
热议问题