我需要异步发送电子邮件。
为此,我有一个jQueryajax客户端和PHP后端来实际发送电子邮件,但ajax的成功方法仍然没有被调用。我知道这很简单,但似乎不起作用。有人能看看我的代码,看看我做错了什么吗?真的很感激。
$.ajax({
type: "POST",
url: "mail.php",
data: {name: "manu", email: "abc@abc.com"},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert('mail sent');
$('#divToBeWorkedOn').html(msg);
}
});
我有邮件.php
<?php
header("Content-type: application/json");
$name = trim($_POST['name']);
echo $name
$email = trim($_POST['email']);
$msg="my email";
$emailTo = 'myemail@gmail.com';
$subject = 'Contact Form Submission from '.$name;
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name 'n'nEmail: $email 'n'nMessage: $message";
$headers = 'From: Saddi website <'.$emailTo.'>' . "'r'n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
echo 1;
?>
我看到两个问题。
-
您只回显1,而不是JSON。因此,在您的PHP代码中执行
json_encode("msg"=>"1");
-
根据我的经验,如果你有这个
header("Content-type: application/json");
或header("Content-type: json/text");
在jquery success
或error
块中不会得到任何结果。
success: function(msg) {
alert(msg);
}
msg将返回null值(或者什么都不返回)。警报会发生,但会显示类似对象对象的内容。