从jQuery.ajax()获取PHP中的JSON
我无法将JSON数据从JavaScript发送到PHP。以下是我的Javascript:从jQuery.ajax()获取PHP中的JSON,php,javascript,ajax,json,null,Php,Javascript,Ajax,Json,Null,我无法将JSON数据从JavaScript发送到PHP。以下是我的Javascript: var noteData = { nData: { "postID": $postID, "commentPar": $commentPar, "commentValue": $commentValue } } var sendData = JSON.stringify(noteData); $.ajax({ type: "PO
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);
告诉您的post请求您正在发送json对象
contentType:“application/json”@Pekka웃 请解释一下?我一开始误读了你的解码(尽管我以为我已经仔细检查过了),对不起。不管怎样,第二个解决方案成功了,第一个仍然给我空值。我想知道哪一种被认为是最佳实践,或者更安全?安全性在双方都是同等的。至于最佳实践,如果需要发送复杂的数据结构,我可能会选择第二种。