Why is json_decode($data, TRUE) converting an array to a string?

限于喜欢 提交于 2019-11-29 15:59:47

Try this. Send your data explicitly as application/json and don't wrap your sendData:

var sendData = {'apps': [[1,2,3], [4,5,6]]};

$.ajax({
  type: 'POST',
  url: 'postTestingResult.php',
  data: JSON.stringify(sendData), // don't wrap your JSONified object 
  contentType: 'application/json' // set application/json - default is x-form-urlencoded
});

Note the headers and data: application/json:

Of course, as you highlighted, the data will not be available in the $_POST superglobal now. However this is not an issue, a very common way to get the JSON data string is to read the raw post data via php://input:

$data = array();
$json = file_get_contents('php://input'); // read JSON from raw POST data

if (!empty($json)) {
    $data = json_decode($json, true); // decode
}

print_r($data);

Yields:

Array( 
  [apps] => Array ( 
    [0] => Array ( 
      [0] => 1 
      [1] => 2 
      [2] => 3 ) 
    [1] => Array ( 
      [0] => 4 
      [1] => 5 
      [2] => 6 
   ) 
))

Hope this helps :)

EDIT

Note that the PHP documentation states:

Note: A stream opened with php://input can only be read once; the stream does not support seek operations.

However, iirc this has or will change (possibly in PHP 5.6?). Don't quote me on that though, and for now, don't forget to assign the contents of that stream if you plan to reuse it!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!