我遇到了jquery验证和ajax表单提交的问题。
这是验证码:
$(function() {
$("#contact-form").validate({
rules: {
name: {
required: true,
minlength: 2,
maxlength: 32
},
email: {
required: true,
email: true
},
message: {
required: true,
minlength: 20
}
},
messages: {
name: {
required: "Please, enter a name",
minlength: $.format("Keep typing, at least {0} characters required"),
maxlength: $.format("Whoa! Maximum {0} characters allowed")
},
email: {
required: "Please, enter an email",
email: $.format("Please, enter valid email")
},
message: {
required: "Please, enter a message",
minlength: $.format("Keep typing, at least {0} characters required")
}
},
submitHandler:function(form) {
form.submit();
}
});
});
这是用于提交表单的ajax代码:
$(document).ready(function(){
$('#contact-form').on('submit',function(e) {
$('#name').val('Your Name');
$('#email').val('Your Email');
$('#message').val('Your Message');
$.ajax({
url:'',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(10000);
},
error:function(data){
$("#error").show().fadeOut(10000);
}
});
e.preventDefault();
});
});
我尝试做的是表单验证,然后提交表单。提交后,表格应再次显示初始值。
问题是当我删除ajax然后验证工作正常,但我需要ajax代码来重新显示表单。
如何让这两段代码一起工作?
答案 0 :(得分:0)
将您的ajax调用放在submitHandler函数中:
submitHandler:function(form) {
//form.submit();
$.ajax({
url:'', //you will need a url surely, perhaps $(form).attr('action');
data:$(form).serialize(),
type:'POST',
success:function(data){
console.log(data);
$('#name').val('Your Name');
$('#email').val('Your Email');
$('#message').val('Your Message');
$("#success").show().fadeOut(10000);
},
error:function(data){
$("#error").show().fadeOut(10000);
}
});
}