$('#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 处理提交事件时,您可以:
- 始终防止正常行为(我们的案例):
- 当表单有效时,您通过 JavaScript提交数据,也许您在提交之前对其进行处理;
- 当表格无效时,您会显示错误消息;
- 仅当表单无效时才阻止正常行为:
- 当表单有效时,您允许正常行为(浏览器提交数据);
- 当表格无效时,您会显示错误消息;
您的案例中的错误消息应说明蜜罐不应为空。
在以下情况下防止正常行为是有意义的: - 您需要在将数据发送到服务器之前对其进行处理(创建新值,更改当前值;而不是验证);- 您需要避免页面刷新,以便通过 AJAX 发送;
只是为了验证,阻止该行为是没有意义的,因为您可以验证然后允许正常行为继续。