jQuery在提交表单之前等待Ajax [英] jQuery Wait for Ajax Before Submitting Form

查看:42
本文介绍了jQuery在提交表单之前等待Ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在提交表单之前完成三个Ajax函数,但是它们也会在提交时触发.

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

什么是强迫jQuery等待所有Ajax函数完成才发送表单的最佳方法?我的代码如下:

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. 首先停止提交(使用 e.preventDefault(); ),
  2. 然后将您的ajax调用包装在 $.when()函数中,
  3. 然后提交表格.

不要忘记在提交之前取消绑定 on('submit')侦听器功能,否则您将陷入无限循环(如 submit()触发 on('submit'),这将触发 submit(),依此类推).

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).

像这样:

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

    e.preventDefault();

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

请参见 https://api.jquery.com/jquery.when/有关$ .when()的更多信息.

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

这篇关于jQuery在提交表单之前等待Ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆