我最近一直在尝试使用Jquery的ajax函数从php获取信息发送请求工作正常,但接收信息不。谢谢你的帮助。
Jquery:$.ajax({
url: 'sendEmail.php',
type: 'post', // performing a POST request
data: values,
dataType: 'json',
success: function(result)
{
console.log("check");//code does not come here
if(result=="Success"){
alert("Your message has been sent. I will get in touch with you soon");
}
else{
alert("Umm.. The meesage was not sent :(. You can still contact me on myemail@gmail.com");
}
}
});
php: <?php
$recipient = 'myemail@gmail.com';
$subject = "Portfolio Message";
$fromName = stripslashes($_POST['Name']);
$fromEmail= stripcslashes($_POST['Email']);
$msg = "Message from: $fromMessage'nEmail: $fromEmail'n'n".stripslashes($_POST['Message']);
if (mail($recipient, $subject, $msg)){
echo "Success";
}
else {
echo "Fail";
}
?>
问题:
响应类型与ajax期望的数据类型不匹配
你有两个选择:
- 将数据类型更改为文本
- 发送一个正确的json响应
两者中的任何一个都将解决您的问题发送json的示例是在json_encode
dataType: 'json',
需要PHP的json回复,在PHP代码中添加header。
<?php
header('Content-Type: application/json');
$recipient = 'myemail@gmail.com';
$subject = "Portfolio Message";
$fromName = stripslashes($_POST['Name']);
$fromEmail= stripcslashes($_POST['Email']);
$msg = "Message from: $fromMessage'nEmail: $fromEmail'n'n".stripslashes($_POST['Message']);
if (mail($recipient, $subject, $msg)){
echo json_encode("Success");
}
else {
echo json_encode("Fail");
}
?>