我有一个 HTML 表单,它使用 div (submitme) 触发以下代码......然后该代码使用 bValidator 插件来验证表单字段,然后在提交表单之前检查蜜 jar 字段是否为空....
当我排除“window.location...”等时,.submit() 可以工作并通过发布表单,但是当包含它时;验证/蜜 jar 仍然有效,但没有表单提交。
我是 JQUERY 新手,想知道是否缺少一些简单的东西或更好的方法来编写以下内容:
$("#submitme").click(function(){
if($('#right-body-div').data('bValidator').validate()) {
if ($("#honeypot").val() == "") {
$('#pgpost').submit();
window.location = "http://www.homepage.co.uk/thankyou";
return true;
}
window.location = "http://www.homepage.co.uk/nothankyou";
return false;
}
});
如果可能的话,我想在不使用 AJAX/PHP 的情况下完成此任务。
非常感谢您的想法。
最佳答案
$('#pgpost').submit(function(e) { // this handles the submit event
if($('#right-body-div').data('bValidator').validate()) {
if ($("#honeypot").val() == "") {
/*
* url = $('#pgpost').val('action');
* data = $('#pgpost').serialize();
* $.post(url, data, function() {
* window.location = "http://www.homepage.co.uk/thankyou";
* });
*/
window.location = "http://www.homepage.co.uk/thankyou";
}
else {
window.location = "http://www.homepage.co.uk/nothankyou";
}
}
e.preventDefault();
return false;
/*
* the 2 lines above are meant to prevent the normal behaviour
* that the <form> would have (which is to submit via browser).
*
* e.preventDefault() is the jquery way prevent the normal behaviour
* return false is the legacy way to do it, you can use either or both
*
* the reason for which the code didn't validate your form is
* that e.prevenDefault() was only called inside the IF statement
* which means that it would only be called if the field was
* already in valid form. So basically if the form was invalid the normal
* behaviour is not prevented and the browser submits the form, if the form
* was valid the submit behaviour was prevented and the redirect was used.
*
*/
});
$("#submitme").click(function(){
$('#pgpost').submit(); // this triggers the submit event
});
通过 JavaScript 处理提交事件时,您可以:
- 始终阻止正常行为(我们的案例):
- 当表格有效时,您submit the data通过 JavaScript,也许您在提交之前对其进行处理;
- 当表单无效时,您会显示错误消息;
- 仅在表单无效时阻止正常行为:
- 当表单有效时,您允许正常行为(浏览器提交数据);
- 当表单无效时,您会显示错误消息;
您的情况中的错误消息应指出蜜 jar 不应为空。
在以下情况下,阻止正常行为是有意义的: - 您需要在将数据发送到服务器之前对其进行处理(创建新值、更改当前值;不验证); - 您需要避免页面刷新,因此通过 AJAX 发送;
仅出于验证目的,阻止该行为没有意义,因为您可以验证然后允许正常行为继续。
关于jquery - .submit() 表单后重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10790187/