简体   繁体   English

如何在JQuery中序列化JSON对象

[英]How to serialize a JSON object in JQuery

I am not able to serialize the JSON object "data", shown below. 我无法序列化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>

Following is the code in file get_note.php: 以下是文件get_note.php中的代码:

<?php

print_r($_POST['data']);
?>

This results in the following being printed to the #note element. 这导致将以下内容打印到#note元素。

Array ( [first_name] => ) 

The array appears to be empty. 该数组似乎为空。 I was expecting a multidimensional array in the PHP file. 我期待PHP文件中有一个多维数组。 Why is it empty? 为什么它是空的?

On the client, you can serialize by doing JSON.stringify() for pure javascript. 在客户端上,您可以通过对纯JavaScript执行JSON.stringify()进行序列化。 On the server, you'll need to do a php json_decode() on the string. 在服务器上,您需要在字符串上执行php json_decode()

So on the client: 因此在客户端上:

var postdata = {'data':JSON.stringify(myObj)};

and on the server: 在服务器上:

$myObj = json_decode(htmlspecialchars_decode($_POST['data']),true);

References: 参考文献:

js JSON.stringify(): http://www.json.org/js.html js JSON.stringify(): http//www.json.org/js.html

php json_decode(): http://php.net/manual/en/function.json-decode.php php json_decode(): http ://php.net/manual/en/function.json-decode.php

You could try sending a serialized JSON array and decrypt it in server side. 您可以尝试发送序列化的JSON数组并在服务器端将其解密。

To serialize JSON array use this: 要序列化JSON数组,请使用以下命令:

var my_json_array = { index: 11 };
JSON.stringify(my_json_array);

Then in server side you can convert (decode) it to PHP array like this: 然后在服务器端,您可以将其转换(解码)为PHP数组,如下所示:

$json = $_POST["my_json_array"];
$my_array = json_decode($json);

So your code would turn in this: 因此,您的代码将显示以下内容:

<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>

and

<?php

print_r(json_decode($_POST['data']));
?>

How it was said, this solution is good for new browsers (with native JSON support) for older ones this solution won`t work. 怎么说呢,该解决方案对于新的浏览器(具有本机JSON支持)适用于较旧的浏览器,但该解决方案将无法使用。

More about JSON support in browsers you can read here: 有关浏览器中JSON支持的更多信息,您可以在这里阅读:

http://en.wikipedia.org/wiki/JSON#Native_encoding_and_decoding_in_browsers http://en.wikipedia.org/wiki/JSON#Native_encoding_and_decoding_in_browsers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM