我试图将值从jQuery传递给PHP。这是我的代码,
jQuery功能:
$(document).ready(function () {
$("#contact_form").submit(function () {
var RequesterName = $("#RequesterName").val();
var Requestoremail = $("#Requestoremail").val();
var Subject = '[Request] Mail Subject';
$.ajax({
type: 'post',
dataType: 'json',
url: 'sendmail.php',
data: { RequesterName_val: RequesterName, Requestoremail_val: Requestoremail, Subject_val: Subject },
success: function (data) {
alert('Mail Sent Successsfully');
}
});
});
})
和PHP:
<?php
$to = $_POST['RequesterName_val'];
$subject = $_POST['Subject_val'];
$RequesterName = $_POST['RequesterName_val'];
$Requestoremail = $_POST['Requestoremail_val'];
$message = "RequesterName:".$RequesterName." , Requestoremail:".$Requestoremail." ";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From: <'.$Requestoremail.'>' . "\r\n";
$headers .= "Reply-To: '.$Requestoremail.'\r\n";
if (mail($to,$subject,$message,$headers)) {
echo "Success";
} else {
echo "Error";
}
die();
?>
似乎邮件是从php触发但是我没有得到回复并且“邮件已成功发送”未在jQuery中显示?如何获得邮件触发器成功和失败的响应?
答案 0 :(得分:1)
您的$.ajax
调用表示响应应为JSON,但您只是返回纯文本。当jQuery尝试解析JSON时出错,它不会调用success:
回调。
您可以更正PHP,以便返回JSON:
echo json_encode(mail($to,$subject,$message,$headers));
die();
然后在success
函数中写下:
success: function(data) {
if (data) {
alert('Mail sent successfully');
} else {
alert('Mail not sent');
}
}
或者您可以更改$.ajax
来电使用dataType: 'text'
,回调将是:
success: function(data) {
if (data == 'Success') {
alert('Mail sent successfully');
} else {
alert('Mail not sent');
}
}