提交 JQuery 表单 $.post() 处理成功时的显示消息

Submit JQuery Form $.post() handle display message on success

本文关键字:成功 显示 消息 处理 表单 JQuery post 提交      更新时间:2023-09-26

我有一个表格,我在jquery中用$.post()提交

$.post("testpage.php", $("#payment-form").serialize())
帖子

本身工作正常,但是当帖子完成并成功时,页面将执行其他操作,例如显示感谢消息和其他内容。我只需要在哪里打电话来显示消息。我不明白从帖子返回的成功走向何方。

您可以为 .post() 指定第三个参数,即"成功"回调。 它是在 .post 执行成功时调用的函数。

$.post("testpage.php", $("#payment-form").serialize(), function() { alert('post was successful!')})

来源: http://api.jquery.com/jquery.post/

简而言之,像这样:

$.post("testpage.php", $("#payment-form").serialize(), function () {
    // Start partying here.
}).fail(function() {
    // Handle the bad news here.
})

或者,您可以使用延迟对象,如下所示:

// Create POST request
var paymentPost = $.post("testpage.php", $("#payment-form").serialize());
// Assigned deferred objects
// "data" refers to the data, preferably in JSON format, returned by testpage.php
paymentPost
.done(function(data) {
    // Success
    // e.g. display thank you message, redirect to a payment successful page...
})
.fail(function(data) {
    // If error
    // e.g. display error message(s)
})
.always(function() {
    // Will always fire as long as POST request is submitted and completed
});

p/s:需要注意的是,像 .success().error() 这样的 jqXHR 方法已被弃用。若要为最终删除它们做好准备,应遵守延迟对象的新命名法;)