问题
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:
- First stop the submission (using
e.preventDefault();
), - Then wrap your ajax calls in a
$.when()
function, - 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