javascript - 如何区分 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 中判断提交事件是成功还是失败,我真的很想知道。
解决方案
好的,正如 Terry 指出的那样,这取决于我们用于验证的内容。
在我们的例子中,我们使用 jquery.validate。有了这个,我们可以在表单上调用 .valid() 来确定表单是否通过了验证:
// If the form successfully submits, the changes are saved
$("form:not(.noprompt)").submit(function (event) {
if ($(this).valid()) {
formHasModifications = false;
}
});
推荐阅读
- html - 使用 CSS 将水平表格转换为垂直表格
- r - 如何使用 gganimate 使注释出现在特定帧上?
- asp.net-core - 使用 Windows 身份验证拦截未经身份验证的请求
- duktape - 在 ECMAscript throw() 之后如何获取错误对象?
- sqlite - 如何从 SQLite 中的数据库表中选择最近的日期?
- python - 将 HTML 表转换为 JSON (Python)
- firebase - 使用自动生成的 ID 将文档添加到 Firestore,并且 ID 具有特定长度
- python - 在 Python 中使用本地函数进行多处理的解决方法?
- jenkins - 如果阶段失败,脚本管道不会停止/退出
- python - 为 Steamlit 中的特定功能清理 st.cache