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。
看起来像'JSON.stringify()'的问题,因为这是嵌套数组变成字符串的时候。尽管如此,仍在思考可能发生的事情。 – Sam
那么,'sendData'是一个对象字面值?你有没有尝试发送它没有'JSON.stringify()'。我不认为你需要JSONify'POST'ed对象文字数据。 –
@Darragh sendData是一个复杂的数据对象。你可以在我链接的pastebin中看到它的JSON.stringify版本。你可以想象它(显然没有键/数据):{[{[{[]},{[]}],{[{[]},{[]}]}],{}} –