首页 > 解决方案 > 如何区分 JQuery 中的提交成功和失败?

问题描述

我正在使用一些 jQuery 来提供未保存的更改警告的旧 ASP.NET/MVC 项目。每个页面都包含一个 utils.js 文件,其中包含:

// Has the user made changes on the form?
var formHasModifications = false;

$(document).ready(function () {

    // We want to trigger the unchanged dialog, if the user has changed any fields and hasn't saved
    $(window).bind('beforeunload', function () {
        if (formHasModifications) {
            return "You haven't saved your changes.";
        }
    });

    // If a field changes, the user has made changes
    $("form:not(.noprompt)").change(function (event) {
        formHasModifications = true;
    });

    // If the form submits, the changes are saved
    $("form:not(.noprompt)").submit(function (event) {
        formHasModifications = false;
    });

    // $(document).ready() may make changes to fields, so we need to clear the flag
    // immediately after it returns
    setTimeout(function() {
        formHasModifications = false;
    }, 1);

});

问题?.submit() 事件在每次提交时触发并被捕获 - 包括在实际未提交数据的提交时。

也就是说,如果出现验证错误,单击提交按钮会使用户留在页面上,并显示未保存的更改并显示验证失败消息,但它也会清除 formHasModifications 标志。

结果是,如果用户对一个或多个输入进行更改,单击“提交”,得到验证错误,然后导航到另一个页面而不修复它们,然后重新提交,即使他们看到了,他们也看不到未保存的更改对话框有未保存的更改。

正如我所说,这是一个遗留应用程序,我对进行根本的结构更改不感兴趣。但是,如果有某种方法能够在 jQuery 中判断提交事件是成功还是失败,我真的很想知道。

标签: javascriptjquery

解决方案


好的,正如 Terry 指出的那样,这取决于我们用于验证的内容。

在我们的例子中,我们使用 jquery.validate。有了这个,我们可以在表单上调用 .valid() 来确定表单是否通过了验证:

// If the form successfully submits, the changes are saved
$("form:not(.noprompt)").submit(function (event) {
    if ($(this).valid()) {
        formHasModifications = false;
    }
});

推荐阅读