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');
}
@Tomalak在评论中提到的现代方式:
as @Tomalak mentioned in the comment, the modern way to do it:
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
可以在此处了解更多信息: jQuery.post().done()和成功:
can read more here: jQuery.post( ) .done( ) and success:
这篇关于jQuery-同步执行2个功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!