[英]Getting JSON in PHP from jQuery .ajax()
我无法将从JavaScript发送的JSON数据发送到PHP。 这是我的Javascript:
var noteData = {
nData: {
"postID": $postID,
"commentPar": $commentPar,
"commentValue": $commentValue
}
}
var sendData = JSON.stringify(noteData);
$.ajax({
type: "POST",
url: templateUrl+"/addnote.php",
data: sendData,
dataType : 'json',
success: function(data) {
alert(data);
console.log(sendData);
},
error: function(e) {
console.log(e.message);
console.log(noteData);
console.log(sendData);
alert("error");
}
});
下面是我如何测试数据是否被传递给PHP,它总是返回null 。
<?php
$nData = json_decode($_POST['nData']);
echo json_encode($nData);
?>
我究竟做错了什么?
您将数据作为原始JSON发送到PHP,而不是POST参数。
有两种选择。 第一个保持PHP完整:
var noteData = {
nData: {
"postID": $postID,
"commentPar": $commentPar,
"commentValue": $commentValue
}
}
var sendData = JSON.stringify(noteData);
$.ajax({
type: "POST",
url: templateUrl+"/addnote.php",
data: {
nData: sendData
},
dataType : 'json',
success: function(data) {
alert(data);
console.log(sendData);
},
error: function(e) {
console.log(e.message);
console.log(noteData);
console.log(sendData);
alert("error");
}
});
第二个单独修改PHP方面。 您需要直接读取输入流以获取原始数据。
<?php
$nData = json_decode(file_get_contents('php://input'));
echo json_encode($nData);
根据服务器配置,这可能略有不同。 请参阅有关输入流包装器的文档。
告诉你的帖子请求你发送json对象contentType:“application / json”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.