ahe*_*ang 1 javascript forms jquery
我有以下代码块:
$(document).ready(function(){
$("#form").submit(function(ev) {
ev.preventDefault();
$.ajax({
type: "POST",
url: "proxy.php",
data: postData,
success: function(data) {
window.location = "thankyou.php";
},
error:function(xhr, ajaxOptions, thrownError){
console.log(xhr.responseText);
}
});
});
$("#form").validate({
//a bunch of validation here
});
});
Run Code Online (Sandbox Code Playgroud)
问题是即使某些验证失败,这将继续使用ajax发布.为什么会这样?我使用ev.preventDefault()的方法是错误的吗?我想要的是,在发送POST之前验证表单如果某些验证失败然后取消,我相信是通过ev.preventDefault()?
在执行ajax请求之前,请测试表单是否有效:
if (!$(this).valid()) return;
Run Code Online (Sandbox Code Playgroud)
您可能也想尝试submitHandler选项:http://docs.jquery.com/Plugins/Validation/validate#options