简体   繁体   English

jQuery 在提交表单之前等待 Ajax

[英]jQuery Wait for Ajax Before Submitting Form

I have three Ajax functions I would like to complete before a form is submitted, but they are also triggered on submit.我想在提交表单之前完成三个 Ajax 函数,但它们也会在提交时触发。

What would be the best way to force jQuery to wait until all Ajax functions complete before the form is sent?在发送表单之前强制 jQuery 等待所有 Ajax 函数完成的最佳方法是什么? My code is as follows:我的代码如下:

$('form[name="regForm"]').on('submit', function() {
    ajaxFuncOne();
    ajaxFuncTwo();
    ajaxFuncThree();
});
  1. First stop the submission (using e.preventDefault(); ),首先停止提交(使用e.preventDefault(); ),
  2. Then wrap your ajax calls in a $.when() function,然后将您的 ajax 调用包装在$.when()函数中,
  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).不要忘记on('submit')之前取消绑定on('submit')侦听器功能,否则您将陷入无限循环(因为submit()将触发on('submit') ,这将触发submit() ,等等)。

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().有关 $.when() 的更多信息,请参阅https://api.jquery.com/jquery.when/

Define a counter variable for tracking how many ajax functions have succeeded, in the scope accessible to all functions.定义一个计数器变量,用于跟踪有多少 ajax 函数成功,在所有函数都可以访问的范围内。 Let's assume it's called c .让我们假设它被称为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.只有当所有三个都成功时,才会提交表单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM