2014-04-04 67 views
2

JavaScript代码:

$.ajax({ 
    type: "POST", 
    url: "postTestingResult.php", 
    data: {data: JSON.stringify(sendData)}, 
    dataType: "json", 
    success: ajaxSuccess, 
    error: ajaxError 
}); 

PHP代码

$data = json_decode($_POST['data'], TRUE); 

当我发布一个复杂的数据结构到服务器,最外面的阵列正在成为一个字符串。例如,JavaScript对象可能是

var data = {"apps": [[1,2,3], [4,5,6]]} 

透过JSON.stringify(数据)这成为

"{"apps": "[[1,2,3], [4,5,6]]"}" //As seen via console.log(data) in Chrome console 

但这样做的json_decode后($ _ POST [ '数据'],TRUE)成为

array('apps' => '[[1,2,3], [4,5,6]]') //As seen via var_export($data, TRUE) 

这是怎么回事?为什么数组被转换为字符串?查看完整的JSON对象和完整的PHP对象check out this pastebin with the two

任何帮助非常感谢,谢谢。

更新:回复发现 我发现了主要的罪魁祸首。我也在使用Prototype.js,并且在对象原型中添加了toJSON方法。 Check out this SO question for details

+0

看起来像'JSON.stringify()'的问题,因为这是嵌套数组变成字符串的时候。尽管如此,仍在思考可能发生的事情。 – Sam

+2

那么,'sendData'是一个对象字面值?你有没有尝试发送它没有'JSON.stringify()'。我不认为你需要JSONify'POST'ed对象文字数据。 –

+0

@Darragh sendData是一个复杂的数据对象。你可以在我链接的pastebin中看到它的JSON.stringify版本。你可以想象它(显然没有键/数据):{[{[{[]},{[]}],{[{[]},{[]}]}],{}} –

回答

3

试试这个。明确地发送数据为application/json,不包住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 
}); 

注意头部和数据:application/json

enter image description here

当然,正如你所强调的,数据将现在不在$_POST超全球范围内。然而,这不是一个问题,得到的JSON数据串一个很常见的方式是通过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); 

产量:

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

希望这有助于:)

编辑

注意,PHP documentation状态:

注:流用PHP打开://输入只能读一次;该流不支持查找操作。

但是,iirc已经或将会改变(可能在PHP 5.6中?)。尽管如此,请不要引用我的意思,而现在,如果您打算重新使用它,请不要忘记指定该流的内容!

+0

当您复制上面的代码或在您的pastebin中使用数据时?你能检查你的请求头来检查你的请求有效载荷吗? –

+0

我忘了重新加载客户端代码:P现在好了,我想,谢谢!但是,物体看起来有点奇怪。例如,我将如何访问以下的app_id? Array([permutation] => Array([permutation_id] => 66)[apps] => [{“app_id”:0,“app_name”:“CvP”}]) –

+0

上面看起来像一个愚蠢的问题,我做$ data ['apps'] [0] ['app_id']我不断收到“PHP警告:非法字符串偏移'app_id'” –