php json parse error,php – 使用$.ajax从json_encode接收响应时获取parseerror

我正在尝试使用$.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是这样的:

$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文本得到警告.

任何帮助将不胜感激.

解决方法:

从ajax调用中删除以下代码并尝试:

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(beemailer.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);

}

});

标签:jquery,json,php,ajax

来源: https://codeday.me/bug/20190625/1283445.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值