在ajax POST方法期间,JSON对象作为NULL接收到服务器

时间:2018-04-18 02:47:25

标签: javascript php json ajax post

搜索周围,似乎无法找到答案。我正在使用ajax发布这个填充了对象的字符串化数组,JSONLint可以使用现在只返回它的php脚本。

然而,在传输过程中,对象变为NULL。我发送JSON字符串的方式有问题吗?我真的很感激为此提出一些建议,会给出虚拟的高五。谢谢你的时间!

JS

  var newDist = $("#distanceEl").val();
    var newDate = $("#dateEl").val();
    var newId = this.arr.length + 1;
    var newStat = new Stat(newId, newDist, newDate);

    this.arr.push(newStat);
    var newData = JSON.stringify(this.arr);
    console.log(newData);

    $.ajax({
        url : "php/post.php",
        type: "POST",
        dataType : "json",
        contentType : "application/json",
        data: newData,

        success: function(response)
        {
            console.log("Ajax: " + JSON.parse(response));
        },

        error: function(requestObject, error, errorThrown)
        {
            console.log("Error with Ajax Post Request:" + error);
            console.log(errorThrown);
        }
    });

PHP

 $jsonData = json_decode($_POST['newData']);
echo json_encode($jsonData);

1 个答案:

答案 0 :(得分:0)

由于您在请求中使用contentType : "application/json",因此您发送的数据不会填充$_POST。您可以使用file_get_contents('php://input')

由于您已经使用JSON.parse

,因此您不需要dataType : "json"回复

在你的js上

$.ajax({
    url : "php/post.php",
    type: "POST",
    dataType : "json",
    contentType : "application/json",
    data: newData,
    success: function(response)
    {
        console.log("Ajax: " , response);
    },
    error: function(requestObject, error, errorThrown)
    {
        console.log("Error with Ajax Post Request:" + error);
        console.log(errorThrown);
    }
});

在你的PHP上:

$input = file_get_contents('php://input');
$jsonData = json_decode($input);
echo json_encode($jsonData);

其他选项是,请勿将您的数据发送为contentType : "application/json"

在你的js:

var newData = [{"id":1,"distance":"1.2mi","date":"1/2/18"},{"id":1,"distance":"2.3mi","date":"1/4/18"},{"id":3,"distance":"1.7mi","date":"1/6/18"},{"id":4,"distance":"defaultDis","date":"defaultDate"}];

$.ajax({
    url : "data.php",
    type: "POST",
    dataType : "json",
    data: {newData : newData}, //Pass your data as object. No need to stringtify newData
    success: function(response)
    {
        console.log("Ajax: " , response);
    },
    error: function(requestObject, error, errorThrown)
    {
        console.log("Error with Ajax Post Request:" + error);
        console.log(errorThrown);
    }
});

在你的PHP上:

echo json_encode($_POST['newData']);