我无法序列化JSON对象"data",如下所示。
<script type="text/javascript">
var myObj = {'first_name':{'answers':{'0':'John'}}};
var postdata = {'data':myObj};
$.post("get_note.php", postdata, function(data){
$('#note').text(data);
});
</script>以下是文件get_note.php中的代码:
<?php
print_r($_POST['data']);
?>这会导致将以下内容打印到#note元素。
Array ( [first_name] => ) 数组似乎是空的。我期望PHP文件中有一个多维数组。为什么它是空的?
发布于 2012-04-13 05:32:30
在客户端,您可以通过对纯javascript执行JSON.stringify()来进行序列化。在服务器端,您需要对字符串执行php json_decode()。
所以在客户机上:
var postdata = {'data':JSON.stringify(myObj)};在服务器上:
$myObj = json_decode(htmlspecialchars_decode($_POST['data']),true);参考文献:
js JSON.stringify():http://www.json.org/js.html
php json_decode():http://php.net/manual/en/function.json-decode.php
发布于 2012-04-13 05:38:18
您可以尝试发送一个序列化的JSON数组,并在服务器端对其进行解密。
要序列化JSON数组,请使用以下命令:
var my_json_array = { index: 11 };
JSON.stringify(my_json_array);然后在服务器端,你可以像这样把它转换(解码)成PHP数组:
$json = $_POST["my_json_array"];
$my_array = json_decode($json);所以你的代码会变成这样:
<script type="text/javascript">
var data = {'first_name':{'answers':{'0':'John'}}};
var postdata = {'data':JSON.stringify(data)};
$.post("get_note.php", postdata, function(data){
$('#note').text(data);
});
</script>和
<?php
print_r(json_decode($_POST['data']));
?>如何说,这个解决方案是好的新浏览器(具有本地JSON支持)对于旧的,这个解决方案将不起作用。
有关浏览器中JSON支持的更多信息,可以在此处阅读:
http://en.wikipedia.org/wiki/JSON#Native_encoding_and_decoding_in_browsers
https://stackoverflow.com/questions/10132152
复制相似问题