将数据从ajax请求解析为json

时间:2016-01-29 19:57:55

标签: php json ajax

我正在尝试将数据从Ajax发送到php页面,我可以毫无困难地发送数据,但是我有从PHP页面访问数据的问题。

我的ajax代码:

 $http({
    method: 'POST',
    url: 'gen/gen_dup.php',
    data: data,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded' 
    }
}).then(function successCallback(response) {
    console.log('Duplicata MB OK', response);
}, function errorCallback(response) {
    console.log('error', response);
});
};

这是我的PHP代码:

$data = json_decode(var_dump($_POST), true);

我从PHP页面得到了回复:

array(1) { ["{"title":"Monsieur","name":"aaa","address":"zzz","reference":"zzzzzzee","collector":"1"}"]=> string(0) "" } 

当我尝试使用以下方式访问它时:

echo $data[0]['reference']; // It doesn't work with $data['reference'] either

我没有结果。如果我使用的话,我将获得相同的数组:

$data = var_dump($_POST);

这让我相信Json解码实际上并没有做任何事情。有什么建议吗?感谢。

1 个答案:

答案 0 :(得分:1)

您正在使用Content-Type: application/x-www-form-urlencoded。您必须相应地序列化您的数据才能使其正常工作。 jQuery.param或AngularJS $httpParamSerializer可以为您执行此操作。

你的帖子没有明确说明,但$http()看起来像AngularJS。在这种情况下:

$http({
    method: 'POST',
    url: 'gen/gen_dup.php',
    data: data,
    transformRequest: $httpParamSerializer //or jQuery.param,
                                           //or $httpParamSerializerJQLike
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded' 
    }
}).then(....

或者您使用Content-Type: application/json而不用担心序列化。

相关问题