【发布时间】:2015-09-15 05:27:27
【问题描述】:
我有一个 jQuery 表单提交例程,它在 ERROR_CHECK.PHP 中有一个输入完整性检查,它依赖于传递给它的 GET 变量进行检查。如果传递给它的值格式不正确,则会出现一个警告框,解释错误以及如何纠正表单数据。需要弹出此警告框,直到表单数据不再格式错误,此时该数据用于重新填充页面上的数据。
因此,在 jQuery 例程中,我受制于我们的朋友 preventDefault(),并且我找到了一个可行但不优雅的解决方案。变量allowSubmit 被初始化为FALSE 并保持这种状态——preventDefault() 也有效——直到表单数据通过完整性检查,此时allowSubmit 切换到TRUE...但只有在提交格式正确的输入数据时发生。这意味着用户必须第二次提交表单,以便表单数据用于替换页面上的数据……当然,这不是解决方案(按两次提交按钮?)
但是,通过动态提交表单(此处,在将 allowSubmit 重置为 TRUE 后立即使用 $('#my_form').submit() statement),我再次提交了表单,从而允许用户一次提交格式正确的数据,如它应该是从一开始。
这显然是一个创可贴的解决方案,并不优雅。谁能看到一种更优雅的方式来构建它? (我正在使用由另一个开发人员设计的 jQuery,这发生在一个较长的自调用 JQuery 函数中,我必须按照自己的条件使用它,以免我不得不重新设计更大的所有其他部分它发生的函数。
这里是代码的提炼(带有自描述变量等),它的工作方式与描述的一样,虽然不像我想要的那样优雅:
var allowSubmit = false;
$('#my_form').on('submit', function(e) {
if (!allowSubmit) {
e.preventDefault();
// Check to see if input data is malformed:
$.get('error_check.php', { new_element_name: $('#new_element_name').val() }, function(data) {
if (data != 0) {
alert("An Error Message that explains what's wrong with the form data");
} else {
allowSubmit = true;
// The line below--an auto-submit--is needed so we don't have to press the submit button TWICE.
// The variable allowSubmit is set to TRUE whenever the submitted form data is good,
// but the code suppressed by e.preventDefault() won't execute until the form is
// submitted a second time...hence the need for this programmatic form submission here.
// This allows the user to correct the errant form data, press the submit button ONCE and continue.
$('#my_form').submit();
}
});
}
$('#element_name').val($('#new_element_name').val());
});
【问题讨论】:
标签: javascript php jquery html forms