我回来了我一直在努力的同一张表格......我的问题是我可以让这个表格正确提交,但错误响应不起作用。我看到响应在控制台中返回并出现错误,但它没有在我的响应中显示我的错误消息......我可以提交空并且我的 jQuery 显示为好像它是成功的,即使我的响应是:{"status":"error","message":"Name is blank"}
或{"status":"error","message":"Email is blank or invalid"}
这是HTML
<div class="span6">
<h4>Ask us anything or request a quote:</h4>
<div id="form" style="padding-top: 1em;">
<form id="contactForm" name="contactForm" method="post">
<div class="controls">
<input class="span6" type="text" name="name" id="name" placeholder="What is your name?" required>
</div>
<div class="controls">
<input class="span6" type="email" name="email" id="email" placeholder="What is your email address?" required>
</div>
<div class="controls">
<textarea rows="3" class="span6" name="message" id="message" placeholder="How can we help you?"></textarea>
</div>
<div class="controls">
<input type="button" class="btn btn-primary" name="formSubmit" id="formSubmit" value="Send E-Mail">
</div>
</form>
</div>
<div id="thanks" style="display:none">
<h3>Thank you for that! <br>
<span class="muted"><small>We appreciate you getting in touch with us...</small></span></h3>
<p>We'll try to get back to you as soon as possible. We know your time is valuable, so we'll try as hard as we can not to waste it.</p>
</div>
<div id="error" style="display: none;">
<h3>Error <span class="muted"> Something in that message did not work right...</span></h3>
<p>Please <a href="#" class="btn btn-danger" id="restForm">CLICK HERE TO RESET THE FORM</a></p>
</div>
</div>
</div>
这是jQuery:
<script>
$(document).ready(function(){
$('#formSubmit').click(function(){
$.ajax({
type: "POST",
url: "php/contact.php",
data: $("#contactForm").serialize(),
dataType: "json",
success: function(msg){
$("#form").fadeOut('fast');
$("#thanks").fadeIn('slow');
$('#contactForm').get(0).reset();
$('form[name=contactForm]').get(0).reset();
},
error: function(){
$("#form").fadeOut('fast');
$("#error").fadeIn('slow');
}
});
});
});
这是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';
} 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);