我正在尝试使用$.ajax via尝试一个非常简单的请求并获得响应. JSON.我已经尝试过从PHP文件中返回一个简单的文本短语.
我的js部分代码就是这样调用beemailer.PHP来获得响应.
$.ajax({
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
url: 'beemailer.PHP',
data: {
'name': data_name,
'email': data_email,
'message': data_message,
'subject': data_subject
},
success: function (data) {
var output = jQuery.parseJSON(data);
console.log(output);
alert(output);
},
error: function (error, x, y) {
console.log(error);
alert(x, y);
}
)
};
而beemailer.PHP是这样的:
<?PHP
$to = "ashish_sharma307@hotmail.com";
$subject = $_POST['subject'];
$message =$_POST['message'];
$headers = "From:".$_POST['name']."(".$_POST['email'].")";
mail($to,$subject,$message,$headers);
$response = "The mail has been sent. Thank You the valid mail.";
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($response);
?>
我现在需要的只是让$response文本得到警告.
任何帮助将不胜感激.
解决方法:
contentType: "application/json; charset=utf-8",
不需要jQuery.parseJSON(data),因为Content-Type是通过以下代码在json中设置和编码的:
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($response);
更新了包含测试数据的代码
JS
$.ajax({
type: 'POST',
dataType: "json",
url : 'beemailer.PHP',
data: {name: 'rai', email: 'rai@test.com', message: 'Test message', subject: 'Test subject'},
success : function(data) {
console.log(data);
alert(data);
},
error: function(error, x, y)
{
console.log(error);
alert(x, y);
}
});
<?PHP
$to = "ashish_sharma307@hotmail.com";
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers = "From:" . $_POST['name'] . "(" . $_POST['email'] . ")";
mail($to, $subject, $message, $headers);
$response = "The mail has been sent. Thank You the valid mail.";
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($response);
?>
对象示例:
$result = array();
$result['status'] = 'success';
$result['message'] = 'The mail has been sent. Thank You the valid mail.';
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($result);
JS访问对象:
$.ajax({
type: 'POST',
dataType: "json",
url : 'beemailer.PHP',
data: {name: 'rai', email: 'rai@test.com', message: 'Test message', subject: 'Test subject'},
success : function(data) {
alert('status: ' + data.status + '\nmessage: ' + data.message);
},
error: function(error, x, y)
{
console.log(error);
alert(x, y);
}
});