我正在努力适应这种提交表单的方法。我正在尝试使用JSON并了解这里发生了什么。。。但我觉得我错过了一些非常明显的东西。。。我真的很想让它发挥作用。非常感谢。
这是HTML
<div class="span4">
<div id="formResponse"></div>
<form id="contactForm" name="contactForm" method="post">
<div class="controls">
<input class="span4" type="text" name="name" id="name" placeholder="Name" required />
</div>
<div class="controls">
<input class="span4" type="email" name="email" id="email" placeholder="E-mail" required />
</div>
<div class="controls">
<textarea rows="3" class="span4" name="message" id="message"placeholder="Leave your message at the beep..."></textarea>
</div>
<div class="controls">
<input type="submit" class="btn btn-primary" name="formSubmit" id="formSubmit" value="Send E-Mail" />
</form>
</div>
</div>
这是jQuery:
<script type="text/javascript">
$(document).ready(function(){
$('#contactForm').submit(function(){
$.ajax({
type: "POST",
url: "php/contact.php",
data: $("#contactForm").serialize(),
dataType: "json",
success: function(msg){
$("#formResponse").removeClass('error');
$("#formResponse").removeClass('success');
$("#formResponse").addClass(msg.status);
$("#formResponse").html(msg.message);
},
error: function(){
$("#formResponse").removeClass('success');
$("#formResponse").addClass('error');
$("#formResponse").html("There was an error submitting the form. Please try again.");
}
});
});
});
</script>
这是PHP:
function checkEmail($email){
if(eregi("^[a-zA-Z0-9_]+@[a-zA-Z0-9'-]+'.[a-zA-Z0-9'-'.]+$]", $email)){
return FALSE;
}
list($Username, $Domain) = split("@",$email);
if(@getmxrr($Domain, $MXHost)){
return TRUE;
} else {
if(@fsockopen($Domain, 25, $errno, $errstr, 30)){
return TRUE;
} else {
return FALSE;
}
}
}
$response_array = array();
if(empty($_POST['name'])){
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Name is blank';
} elseif(!checkEmail($_POST['email'])) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Email is blank or invalid';
} elseif(empty($_POST['message'])) {
$response_array['status'] = 'error';
$response_array['message'] = 'Message is blank';
} else {
//send the email
$body = $_POST['name'] . " sent you a message'n";
$body .= "Details:'n'n" . $_POST['message'];
mail($_POST['email'], "SUBJECT LINE", $body);
//set the response
$response_array['status'] = 'success';
$response_array['message'] = 'Email sent!';
}
echo json_encode($response_array);
您没有指定什么不起作用,但我可以立即看到您没有阻止默认的表单提交行为,这是一个问题:
$('#contactForm').submit(function (e) {
e.preventDefault();
这会阻止表单正常提交,因此将使用ajax。我没有看到其他不愉快的事情。
您还可以删除<input type="submit" class="btn btn-primary" name="formSubmit" id="formSubmit" value="Send E-Mail" />
并将其替换为<input type="button" class="btn btn-primary" name="formSubmit" id="formSubmit" value="Send E-Mail" />
在你的jquery中使用这个:-
$('#formSubmit').click(function(){});
而不是:-
$('#contactForm').submit(function(){});
这将防止表单默认的张贴行为。其次,如果您在localhost上运行代码,请确保安装了邮件服务器,以便使用php-mail()函数。