简体   繁体   English

JSON解码问题

[英]JSON decode problems

When I post a text with Ajax, like this: 当我使用Ajax发布文本时,如下所示:

var text = encodeURIComponent(transtext);

and receive it with PHP: 并通过PHP接收:

$text=$_POST['text']

it seems that PHP automatically decodes the encoded string. 看来PHP会自动解码编码的字符串。 Is there any way to avoid this? 有什么办法可以避免这种情况?

Ok here is my original Json string that i want to post with ajax: 好的,这是我想用ajax发布的原始Json字符串:

{"1":"\\"sdfsdfsdf" as&das&d ","2":"asdasd"}

I have to encodeURIComponent the string inside so i can post it json.strigify that dont encode &: 我必须要编码里面的字符串,所以我可以将它发布为json.strigify而不编码&:

{"1":"%22asdasd%5C%22asdasd%22asdasd%26asdasd","2":"asdasd"}

But when i receive the string in PHP the " make fail the jsondecode because i get 但是,当我在PHP中收到字符串时,“会使jsondecode失败,因为我得到了

POST={"1":""sdfsdfsdf" as&das&d ","2":"asdasd"}

Any ideas? 有任何想法吗?

This function ( encodeURIComponent() ) does not produce JSON. 此功能( encodeURIComponent() 产生JSON。

It produces an URL-encoded string, and these are decoded by the server automatically. 它产生一个URL编码的字符串,并由服务器自动解码。 I don't see why you would not want that. 我不明白为什么你不想要那个。

URL-encoding is a pure transport encoding, its purpose in life is to make sure the data you send to a server is suitable for transfer via HTTP GET or POST, and that it is not garbled on its way. URL编码是一种纯传输编码,其作用是确保发送到服务器的数据适合通过HTTP GET或POST进行传输,并且不会出现乱码。 That the server decodes it for you before filling the $_GET , $_POST and $_REQUEST arrays is the right thing to do. 服务器在填充$_GET$_POST$_REQUEST数组之前为您解码它是正确的事情。 It makes sure the data is in the same shape it was before it was sent from the client. 它可以确保数据的形状与从客户端发送数据之前的形状相同。

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

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