php - 从 jQuery .ajax() 在 PHP 中获取 JSON

标签 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: "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/

相关文章:

PHP while 循环中的第二个 while 循环仅运行一次

javascript - ReferenceError:未定义电子

php - 允许用户在运行时向表单添加字段

javascript - 如何验证 cucumberjs/puppeteer 中不存在的选择器?

javascript - 将 JS 变量设置为 $.get 请求

javascript - 当我执行ajax并返回错误时,Jquery获取自定义响应内容

php - php中如何获取嵌套数组的值

javascript - 文本突出显示。替换开始和结束位置处的文本

javascript - 带有预加载延迟的 jQuery 工具叠加

css - 更新进度面板、CSS 和删除内联样式