我想创建一个基于 jquery 验证插件 ( http://docs.jquery.com/Plugins/Validation ) 的评论表单。如何配置表单以使用 AJAX 提交?现在我无法在不进入下一页(process.php)的情况下提交表单。我希望它保留在表单页面上。
当前代码几乎直接来自 jquery。
<script>
$(document).ready(function () {
$("#commentForm").submit(function () {
if ($("#commentForm").validate()) {
$.ajax({
type: 'POST',
url: 'process.php',
data: $(this).serialize(),
success: function (returnedData) {
$('#commentForm').append(returnedData);
}
});
}
return false;
});
});
</script>
<form class="cmxform" id="commentForm" method="POST" action="process.php">
<label for="cname">Name</label>
<em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" />
<label for="cemail">E-Mail</label>
<em>*</em><input id="cemail" name="email" size="25" class="required email" />
<label for="curl">URL</label>
<em> </em><input id="curl" name="url" size="25" class="url" value="" />
<label for="ccomment">Your comment</label>
<em>*</em><textarea id="ccomment" name="comment" cols="22" class="required"></textarea>
<input class="submit" type="submit" value="Submit"/>
PHP 也非常标准:
<?php
$to = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8cffe8eaffede8eaffffeaedffe8ccebe1ede5e0a2efe3e1" rel="noreferrer noopener nofollow">[email protected]</a>';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c6b797e717d6f68796e5c79647d716c7079327f7371" rel="noreferrer noopener nofollow">[email protected]</a>' . "\r\n" .
'Reply-To: <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9aebcbbb4b8aaadbcab99bca1b8b4a9b5bcf7bab6b4" rel="noreferrer noopener nofollow">[email protected]</a>' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
print "Form submitted successfully: <br>Your name is <b>".$_POST['cname']."</b> and your email is <b>".$_POST['email']."</b><br>";
?>
感谢您的帮助。
最佳答案
$(document).ready(function(){
$("#commentForm").submit(function(){
if($("#commentForm").validate()){
$.ajax({
type: 'POST',
url: 'process.php',
data: $(this).serialize(),
success: function(returnedData){
alert(returnedData);
}
});
}
return false;
});
});
关于php - AJAX Jquery PHP 表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9353135/