我正在用PHP编写邮件发件人,并使用jQuery通过ajax调用它。这是我的PHP代码的一部分:
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
这是我的JS:
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#nombre').val('');
$('#email').val('');
$('#telefono').val('');
$('#pais').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('success');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
HTML表单,以防万一:
<form id="ajax-contact" method="post" action="mailer.php">
<ul>
<li><input name="nombre" id="nombre" class="inputNombre" placeholder="Nombre" required/></li>
<li><input name="email" id="email" placeholder="E mail" type="email" class="inputEmail" required/></li>
<li><input name="telefono" placeholder="Teléfono" class="inputTelefono" id="telefono" required/></li>
<li><input name="pais" placeholder="País" class="inputPais" id="pais" required /></li>
<li><input name="submit" type="submit" value="Enviar" class="botonEnviar" id="submit"></input></li>
</ul>
</form>
这里奇怪的是,即使发送了邮件,这也总是转到else
分支并设置500代码,所以当我尝试管理响应时,我得到了错误的代码。但我收到了邮件,因此if
正在运作。
我总是得到响应代码500,据说是在邮件发生故障时设置的。
我做错了什么?
答案 0 :(得分:0)
尝试添加elseif(!)
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
}
elseif (!mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
答案 1 :(得分:0)
检查您的网络托管的PHP版本。您只能从PHP 5.4中设置response codes。 编辑:我今天遇到了完全相同的问题。邮件消失了,PHP返回500响应。我尝试在PHP 5.5.21的另一台服务器上运行代码,它运行得很完美。