我在将 JSON 数据从 JavaScript 发送到 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);
根据服务器配置的不同,这可能会略有不同。请参阅 input stream wrappers 上的文档.
关于php - 从 jQuery .ajax() 在 PHP 中获取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17000043/