我正在使用 jQuery 的验证插件在进行 Ajax 调用之前验证表单,但由于某种原因,每次我提交表单时页面都会刷新。这是我的验证功能:
//Invite form validation
$("#inviteForm").validate({
//Rules for invite validation
rules: {
name: "required",
email: {
required: true,
email: true
}
},
//Messages to print if validation fails
messages: {
name: "Please provide your friend's name.",
email: "We cannot contact your friend without a valid email address.",
},
//What to do when validation succeeds
submitHandler: function(form) {
//Form is valid, make Ajax call
$.ajax({
type: "POST",
url: '/invite/process',
data: $("#inviteForm").serialize(),
datatype: "html",
success: function(data, textStatus ,XHR) {
$("#inviteModal").html(data);
if(data.indexOf("Thank you") >= 0 ){
invites -=1;
$("#overlay").css("display", "none");
$("#inviteModal").fadeOut(5000);
}
}
});
return false;
}
});
我将它放在 a$(document).ready
中,但我没有发布整个内容,因为那里还有一些其他功能。这是表单的代码:
<!--// MODAL: INVITE //-->
<div id="inviteModal" class="modal" style="display: none">
<script type="text/javascript" src="/includes/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var invites = <?php echo $user->getInvitesLeft(); ?>;
if(invites < 1){
$("#inviteModal").html("You have no invites left. You can get more by increasing your score.");
}
else{
$("#inviteModal").html("<h2>Please enter the specified information for the friend you wish to invite. </h2>"+
"<form id=\"inviteForm\" >"+
"<p>Name: <input type=\"text\" name=\"name\"></p>"+
"<p>Email: <input type=\"text\" name=\"email\"></p>"+
"<p><input type=\"submit\" name=\"submit\" value=\"Invite\"></p>"+
"</form>");
}
</script>
</div>
每当我提交表单时,它会刷新页面而不执行 Ajax 调用并将表单数据添加到 URL,例如?name=bobby&email=williamrump%40aol.com&submit=Invite。为什么它会在不进行 Ajax 调用的情况下刷新页面,我可以做些什么来阻止它?