我无法序列化 JSON 对象“数据”,如下所示。
<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 文件中有一个多维数组。为什么是空的?
最佳答案
在客户端,您可以通过对纯 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
关于javascript - 如何在 JQuery 中序列化 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10132152/