简体   繁体   English

jQuery-同步执行2个功能

[英]jQuery - Execute 2 functions synchronously

I have created a submit function for each form created on my application. 我已经为在应用程序上创建的每个表单创建了一个提交功能。 It's similar to the one written below. 它类似于下面的内容。

$('form').submit(function(){
  //Some variable declaration
  $.ajax({
   type:'post',
   url:'someurl',
   data:formdata
   success:function(){
     console.log('form submitted');
   }
  });
});

No doubt this works fine. 毫无疑问,这很好。 Now for one of the forms I want to update a certain element after the response is received, similar to this. 现在,对于其中一种形式,我想在收到响应后更新某个元素,类似于此。

$('#customform').submit();
console.log('custom form submitted');

So in this case I want the message "custom form submitted" to be printed only after 'form submitted' message is printed to the console (Synchronous loading). 因此,在这种情况下,我希望仅在将“表单提交”消息打印到控制台(同步加载)之后才打印“自定义表单提交”消息。 Anyone to help? 有人帮忙吗?

Just include the code into the success function: 只需将代码包含到成功函数中即可:

success:function(){
  console.log('form submitted');
  console.log('custom form submitted');
}

You can also add complete function, so the code will run no matter if error or success: 您还可以添加完整功能,因此无论错误或成功,代码都将运行:

success:function(){
  console.log('form submitted');
},
complete: function() {
  console.log('custom form submitted');
}

as @Tomalak mentioned in the comment, the modern way to do it: 正如@Tomalak在评论中提到的那样,现代的方法是:

var jqxhr = $.post( "example.php", function() {
  alert( "success" );
})
.done(function() {
  alert( "second success" );
})
.fail(function() {
  alert( "error" );
})
.always(function() {
  alert( "finished" );
});

can read more here: jQuery.post( ) .done( ) and success: 在这里可以阅读更多内容: jQuery.post().done()和成功:

I would take off $("form").submit eventlistener after forms finished submit, and add a custom one into it's success function $("form").submit完成后,我将取消$("form").submit eventlistener,并向其成功函数添加一个自定义变量

$("form").submit(function(){
    $.ajax({
        type:"post",
        url:"someurl",
        data:formdata,
        success:function(){
            console.log("form submitted");
            $("form").off("submit");

            $("#customform").submit(function(){
                $.ajax({
                    type:"post",
                    url:"someurl",
                    data:modifiedFormdata,
                    success:function(){
                        console.log("custom form submitted");
                    }
                });
            }); 
        }
    });
});

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

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