使用 JavaScript / jQuery 提交表单后调用函数

Spr*_*Gr8 5 javascript forms jquery

我想在提交表单后调用一个函数,我看到我们可以在 jQuery 中执行此操作,.submit(handler function())但是方法描述说,处理程序方法将在提交表单之前执行。我怎样才能真正做到这一点?我应该setTimeout在提交表单后使用还是有其他解决方案?

ade*_*neo 5

$("#myFormId").on('submit', function(e) {
    e.preventDefault();
    $.ajax({
        type: $(this).prop('method'),
        url : $(this).prop('action'),
        data: $(this).serialize()
    }).done(function() {
        doYourStuff();
    });
});
Run Code Online (Sandbox Code Playgroud)

  • 这不是在提交表单“之后”调用函数 (3认同)

Mih*_*hai 0

您可以使用插件http://www.malsup.com/jquery/form/#ajaxSubmit并在回调方法成功时执行您需要的操作

$(document).ready(function() { 
var options = { 
    target:        '#output2',   // target element(s) to be updated with server response 

    success:       function() {
                   // callback code here
                    }

}; 

// bind to the form's submit event 
$('#myForm2').submit(function() { 
    $(this).ajaxSubmit(options); 

    return false; 
}); 
}); 
Run Code Online (Sandbox Code Playgroud)