jQuery Wait for Ajax Before Submitting Form

北城余情 提交于 2021-02-02 09:51:05

问题


I have three Ajax functions I would like to complete before a form is submitted, but they are also triggered on submit.

What would be the best way to force jQuery to wait until all Ajax functions complete before the form is sent? My code is as follows:

$('form[name="regForm"]').on('submit', function() {
    ajaxFuncOne();
    ajaxFuncTwo();
    ajaxFuncThree();
});

回答1:


  1. First stop the submission (using e.preventDefault();),
  2. Then wrap your ajax calls in a $.when() function,
  3. Then submit the form.

Don't forget to unbind the on('submit') listener functionality before submitting, else you will end up in an infinite loop (as submit() will be triggering on('submit'), which will be triggering submit(), and so forth).

Like so:

$('form[name="regForm"]').on('submit', function(e) {

    e.preventDefault();

    $.when(
        ajaxFuncOne();
        ajaxFuncTwo();
        ajaxFuncThree();
    ).done(function(){
        $('form[name="regForm"]').unbind('submit').submit();
    });
});

See https://api.jquery.com/jquery.when/ for more information on $.when().




回答2:


Define a counter variable for tracking how many ajax functions have succeeded, in the scope accessible to all functions. Let's assume it's called c. Then, prevent submission if it is not equal to three. Disable the button to avoid further clicks.

$('form[name="regForm"]').on('submit', function() {
  if(c < 3) {
    e.preventDefault();
    $(this).attr('disabled','disabled');
    ajaxFuncOne();
    ajaxFuncTwo();
    ajaxFuncThree();
  }
});

Then call the following in each success handler.

function track() {
  if(++c == 3) $('form[name="regForm"]').submit();
}

Only when all three have succeeded, will the form be submitted.



来源:https://stackoverflow.com/questions/43326088/jquery-wait-for-ajax-before-submitting-form

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!