What we're going to bring to you today is a workaround for the PHP json_encode function when it comes to handling Chinese conversions. JSON is a good data structure that is now widely used in network data transmission,
Json_encode and Json_decode
The specific use of the two functions on the internet has a lot of relevant articles, this article mainly introduces the Json_encode when the Chinese can not be converted to the solution, this paper assumes that the code used in the file is gb2312;
First, write the array you want.
- < ? Php
- $ JSON = Array (
- 0 = >
- Array (
- ' id ' = > ' A ',
- ' name ' = > ' ping-pong ',
- ),
- 1 = >
- Array (
- ' id ' = > ' + ',
- ' name ' = > ' Basketball ',
- )
- )
- ?>
If you use the PHP json_encode function directly
- < ? Php
- echo Json_encode ($json);
- ?>
The result is:
- < ? Php
- [{"id": "+", "name": null}
, {"id": "+", "name": null}]
- ?>
You can see that Chinese characters are not escaped null because JSON simply escapes the encoding encoding, so the above statement should first convert the encoding
- < ? Php
- foreach ($ajax as $key=>$val)
- {
UrlEncode ($val [' name ']);
- }
- echo Json_encode ($json);
- ?>
Client JS Code
- < script type="text/javascript">
- function Getsort (obj)
- {
- $.ajax (
- {
- Type: "GET",
- URL: " < ? = $this- > BASEURL ?> /index/getajax ",
- data: " C = "Obj.value,
- Success:function (JSON)
- {
- var JSON = Eval (JSON);
- var HTML = ' < select> ' ;
- $.each (JSON, function (k)
- {
- HTML = ' < option value= '
json[k][' id '] '>'
decodeURI (json[k][' name ']) '< /option>';
- });
- HTML = "</select>" ;
- $ (' #sort '). HTML (HTML);
- }
- }
- )
- }
- < /script >
Use the above code JS will error said code does not meet the standard
The reason is because JS in decodeURI only support UTF8 transcoding. So, the code for the PHP Json_encode function should be the following code
- < ? Php
- foreach ($ajax as $key=>$val)
- {
UrlEncode (Iconv (' gb2312 '),
' Utf-8 ', $val [' name ']);
- }
- echo Json_encode ($json);
- ?>
The above is the solution to the problem in the actual operation using PHP Json_encode function.
http://www.bkjia.com/PHPjc/446101.html www.bkjia.com true http://www.bkjia.com/PHPjc/446101.html techarticle What we're going to bring to you today is a workaround for the PHP json_encode function when it comes to handling Chinese conversions. JSON is a good data structure that is now widely used in Web ...