正在尝试设置联系表格。表单提交电子邮件和可选的抄送发件人。如果启用了 javascript,表单将提交到 contact-ajax.php(用感谢消息替换表单),否则提交到 contact.php(重定向到感谢页面)。后备表单工作正常,但每次 ajax 表单触发时,它也会发送一封完全空白的电子邮件(如果选中了 CC 选项,则发送给发件人和收件人)。我无法弄清楚为什么会发生这种情况。任何见解将不胜感激。
表单 HTML:
<form method="post" id="email_form" name="email_form" action="contact.php">
<label for="name">Name:</label><br />
<input type="text" name="name" id="name" placeholder="John Doe" /><br />
<label for="email">Email Address:</label><br />
<input type="text" name="email" id="email" placeholder="johndoe@gmail.com" /><br />
<label for="subject">Subject </label></td><br />
<input type="text" name="subject" id="subject" placeholder="Subject" /><br />
<label for="message">Message:</label></td><br />
<textarea cols="35" rows="5" name="message" id="message" placeholder="Your Message"></textarea><br />
<input type="checkbox" name="cc" id="cc" checked value="Yes" /><label for="cc"> Send yourself a copy of this message</label><br />
<input class="submit pulldown button" name="submit" id="submit" type="submit" value="Send Message" />
</form>
Javascript:
$(document).ready(function() {
$('#email_form #submit').click(function(event) {
event.preventDefault();
$.ajaxSetup ({
cache: false
});
$.ajax({
type: 'POST',
url: 'contact-ajax.php',
data: $("#email_form").serializeArray(),
success: function(msg) {
if(msg=='Mail sent') {
alert(msg);
}
else {
alert('Error sending mail. Please try again.');
}
},
error: function(ob,errStr) {
alert('Error sending mail. Please try again.');
}
});
return false;
});
});
脚本调用的 PHP 表单 (contact-ajax.php):
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$email_subject = $_POST['subject'];
$message = $_POST['message'];
$today = date('r');
$email_from = "address@domain.tld";
$to = "address@domain.tld";
$email_body = "On $today $name wrote:\n"."$message";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
if (isset($_POST['cc'])) {
$headers .= "CC: $visitor_email \r\n";
}
$headers .= "X-Mailer: PHP/". phpversion();
mail($to,$email_subject,$email_body,$headers);
if(mail($to, $subject, $body, $headers)) {
die('Mail sent');
}
else {
die('Error: Mail failed');
}
}
?>
非 Ajax php 脚本 (contact.php) 是相同的,只是它以header('Location: thanks_page.html');
而不是最后一条if
语句结尾。
空白电子邮件不包含主题或消息正文,但 From、Reply-To 和 CC 字段都完全按照正确(非空)消息中的内容填写。几天来我一直试图找出问题所在,但似乎无法找到它。