我网站上的表格是一个简单的联系表格。我希望表单在发送/失败时在同一页面上显示"成功和失败"消息,而不重新加载页面。我知道我应该使用Ajax来做到这一点,但我无法让它发挥作用,因为我对它的了解很少。
这是我正在使用的代码。
Html(单页设计):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>
<form class="form" id="contactus" action="" method="post" accept-charset="UTF-8">
<label for="nametag">Namn<FONT COLOR="#FF0060">*</FONT></label>
<input name="name" type="text" id="name" value="" />
<label for="emailtag">Email<FONT COLOR="#FF0060">*</FONT></label>
<input name="email" type="text" id="email" value="" />
<label for="phonetag">Telefon</label>
<input name="phone" type="text" id="phone" value="" />
<label for="messagetag">Meddelande<FONT COLOR="#FF0060">*</FONT></label></br>
<textarea name="message" id="message" style="width: 87%; height: 200px;"></textarea>
<label class="placeholder"> </label>
<button class="submit" name="submit">Skicka</button>
</form>
<script>
$(function() {
$('#contactus').submit(function (event) {
event.preventDefault();
event.returnValue = false;
$.ajax({
type: 'POST',
url: 'php/mail.php',
data: $('#contactus').serialize(),
success: function(res) {alert(res);
if (res == 'successful') {
$('#status').html('Sent').slideDown();
}
else {
$('#status').html('Failed').slideDown();
}
},
error: function () {
$('#status').html('Failed').slideDown();
}
});
});
});
</script>
Php:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$recipient = "info@mydomain.com";
$subject = "Webbkontakt";
$formcontent = "Från: $name <br/> Email: $email <br/> Telefon: $phone <br/> Meddelande: $message";
$headers = "From: " ."CAMAXON<info@mydomain.com>" . "rn";
$headers .= "Reply-To: ". "no-reply@mydomain.com" . "rn";
$headers .= "MIME-Version: 1.0rn";
$headers .= "Content-Type: text/html; charset=utf-8rn";
if(mail($recipient, $subject, $formcontent, $headers))
{
echo "successful";
}
else
{
echo "error";
}
?>
您的Ajax
调用工作不正常。试试这个
$(function() {
$('#contactus').submit(function (event) {
event.preventDefault();
event.returnValue = false;
$.ajax({
type: 'POST',
url: 'php/mail.php',
data: $('#contactus').serialize(),
success: function(res) {
if (res == 'successful') {
$('#status').html('Sent').slideDown();
}
else {
$('#status').html('Failed').slideDown();
}
},
error: function () {
$('#status').html('Failed').slideDown();
}
});
});
});
同样,正如你所看到的,我以这种方式使用了$('#contactus').serialize()
,你不需要一个接一个地传递表单元素,而是serialize()
会将整个表单元素传递到你的php页面
如果一切顺利,则在您的php文件echo
successful
中;如果响应为error
,则在echo
error
中显示error div
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$recipient = "info@mydomain.com";
$subject = "Webbkontakt";
$formcontent = "Från: $name <br/> Email: $email <br/> Telefon: $phone <br/> Meddelande: $message";
$headers = "From: " ."CAMAXON<info@mydomain.com>" . "rn";
$headers .= "Reply-To: ". "no-reply@mydomain.com" . "rn";
$headers .= "MIME-Version: 1.0rn";
$headers .= "Content-Type: text/html; charset=ISO-8859-1rn";
if(mail($recipient, $subject, $formcontent, $headers))
{
echo "successful";
}
else
{
echo "error";
}
?>
这样更改您的PHP脚本:
<?php
if( isset( $_POST['submit'] )){ //checking if form was submitted
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$formcontent="Meddelande: nn $message";
$recipient = "info@mydomain.com";
$subject = "Webbkontakt";
$mailheader = "Från: $name n Email: $email n Telefon: $phone rn";
$mailsent = mail($recipient, $subject, $formcontent, $mailheader);
if($mailsent) echo "Success"; //success if mail was sent
else echo "Ett fel uppstod!";
}
?>
在mail()
函数下面,只需执行echo "successful";
2020编辑
在REST API中,响应应始终伴随正确的HTTP状态代码,200+告诉客户端该请求最终得到了正确处理或其他方面良好,400+告诉客户端请求中有错误,500+告诉客户端服务器本身有问题。不要在响应中使用状态,这是对现有功能的不必要复制:
http_response_code(200);
echo json_encode(['message' => 'Email was sent']);
exit;
然后您可以使用jQuery处理请求和响应(假设您仍然使用jQuery):
$.ajax({
url: url,
data: data,
dataType: 'json'
})
.then(function (data, textStatus, jqXHR) {
// Your 200+ responses will land here
})
.fail(function (jqXHR, textStatus, errorThrown) {
// Your 400+ responses will be caught by this handler
});
;
如果您需要特定的状态,可以使用jqXHR.status
字段从jqXHR
参数中获取。
原始答案
您可以在ajax
呼叫中使用dataType: 'json'
。
然后,您就可以将状态代码作为响应密钥:
// form response array, consider it was success
$response = array( 'success'=> 'ok', 'message' => 'Email was sent');
echo json_encode($response);
在js中,您可以检查data.success === 'ok'
以了解您的状态。
在php脚本中,您可以尝试这个
if(mail($recipient, $subject, $formcontent, $mailheaders))
{
echo("Mail Sent Successfully"); // or echo(successful) in your case
}else{
echo("Mail Not Sent"); // or die("Ett fel uppstod!");
}