我正在努力适应这种提交表单的方法。我正在尝试使用 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);