JSON stringify后的json_decode不能正常工作


json_decode after JSON stringify not working properly

我有一个javascript数组,这是json编码并发布到PHP。当我在发布之前检查数组中的值时比如console.log(selection[878][2824]),我得到一个值作为结果。然后变量是json编码使用JSON.stringify和发布到服务器。但是当我在php中json_decode值并打印相同时,我得到空数组

<<p> js脚本/strong>
    console.log(selection);
    $http({
                method: 'POST',
                url: 'example.php',
                data: 'selection='+JSON.stringify(selection),
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            })
php脚本

$selectionData = json_decode($_POST['selection']);
print_r($selectionData[878][2824]);

那么在这里编码数据时发生了什么呢?它是如何丢失的?

似乎数据没有正确格式化,我认为你必须格式化字符串在

"selection :"  +JSON.stringify(selection);

try this

js

$http({
            method: 'POST',
            url: 'example.php',
            data: {selection : JSON.stringify(selection)}
        })
php

$data = json_decode(file_get_contents("php://input"),true);
$selection = json_decode($data['selection'],true);

当您使用POST时,您不必对内容进行字符串化,只需设置正确的标题。

$http({
            method: 'POST',
            url: 'example.php',
            data: selection,
            headers: {'Content-Type': 'application/json'}
        })

或者如果你需要一个标识符:

$http({
            method: 'POST',
            url: 'example.php',
            data: {"selection": selection },
            headers: {'Content-Type': 'application/json'}
        })

和在PHP中(如果你使用额外的标识符):

$selectionData = $_POST['selection'];