我正在制作一个查询表格。我是 jquery 的新手。在阅读了 jquery 验证插件和 ajax 之后,我编写了以下代码。此代码首先验证表单,然后通过 ajax 提交表单。如果我提交表格,表格提交两次。结果来了两次我无法出错。
<script>
$(document).ready(function () {
$('#contactForm').validate({
rules: {
name: {
required: true
},
email: {
required: true,
email: true
},
address: {
required: true
},
message: {
required: true
},
security: {
required: true
}
},
messages: {
name: {
required: '* Please Enter Your Name.'
},
email: {
required: "* Please Enter Your E-mail ",
email: "* Please enter proper E-mail "
},
address: {
required: "* Please enter address."
},
message: {
required: "* Please enter Enquiry"
},
security: {
required: "* Please enter Security code"
}
},
submitHandler: function (form) {
// Ajax Submit here
// alert($("#contactForm").serialize());
$.ajax({
type: "POST",
url: "assets/sendmail.php",
data: $("#contactForm").serialize(),
success: function (result) {
if (result == 'Success') {
$("#contactForm").hide();
$("#contact_response").html('<div class="alert alert-success">Thank you for your feedback.</div>');
} else {
alert(result);
}
return false;
}
});
return false;
}
});
});
html表单是
<form action="assets/sendmail.php" method="post" name="contactForm" id="contactForm" >
<!-- STEP-2 : GENERAL SETTINGS -->
<input type="hidden" name="success_page" value="../contact-us?res=thank-you" id="success_page" /><!-- PAGE TO REDIRECT AFTER SUBMIT -->
<input type="hidden" name="email_to" value="<?=get_settings('contact_email');?>" id="email_to" /><!-- EMAIL ADDRESS WHERE WE WANT TO RECEIVE EMAIL -->
<input type="hidden" name="email_subject" value="Query Recieved" id="email_subject" /><!-- SUBJECT OF THE EMAIL -->
<!-- STEP-2 : GENERAL SETTINGS -->
<label for="name" class="nameLabel">Name</label>
<input id="name" type="text" name="name" />
<label class="control-label">Email address</label>
<div class="controls">
<input type="email" name="email" id="email" />
<p class="help-block"></p>
</div>
<label for="address">Address</label>
<input id="address" type="text" name="address" />
<label for="message" class="messageLabel">Enquiry</label>
<textarea id="message" name="message" /></textarea>
<label >Security Code</label>
<img src="classes/CaptchaSecurityImages.php?width=100&height=30&characters=5" alt="captcha" style="vertical-align:bottom;"/> <input id="security" name="security" class="required" type="text" style="width:30%;vertical-align:bottom;margin-bottom:0px;padding-bottom:0px;"/></br>
<button type="submit" id="submit" name="submit">Send</button>
</form>
</script>