Home > Backend Development > PHP Tutorial > javascript - AJAX返回中文乱码

javascript - AJAX返回中文乱码

WBOY
Release: 2016-06-06 20:32:29
Original
1495 people have browsed it

取来的json数据中文显示 \u5fd9\u5364\u9e25\u732b\u9225\u5b64\u5f9d

这是什么编码?

服务端用iconv('GBK', 'UTF-8',$out)不管用,直接取也是乱码,数据库写入用的utf-8

回复内容:

取来的json数据中文显示 \u5fd9\u5364\u9e25\u732b\u9225\u5b64\u5f9d

这是什么编码?

服务端用iconv('GBK', 'UTF-8',$out)不管用,直接取也是乱码,数据库写入用的utf-8

\u5fd9\u5364\u9e25\u732b\u9225\u5b64\u5f9d是unicode编码

应该是unicode编码,使用unescape解码:

<code>str=" \u5fd9\u5364\u9e25\u732b\u9225\u5b64\u5f9d";
unescape(str.replace(/\\u/gi, "%u"));
" 忙卤鸥猫鈥孤徝"
</code>
Copy after login

但是感觉也不像,请确认一下

<code><?php $a = '\u5fd9\u5364\u9e25\u732b\u9225\u5b64\u5f9d';

echo unicode_decode($a);

function unicode_decode($name)
{
    // 转换编码,将Unicode编码转换成可以浏览的utf-8编码
    $pattern = '/([\w]+)|(\\\u([\w]{4}))/i';

    preg_match_all($pattern, $name, $matches);
    if (!empty($matches))
    {
        $name = '';
        for ($j = 0; $j < count($matches[0]); $j++){
            $str = $matches[0][$j];
            if (strpos($str, '\\u') === 0)
            {
                $code = base_convert(substr($str, 2, 2), 16, 10);
                $code2 = base_convert(substr($str, 4), 16, 10);
                $c = chr($code).chr($code2);
                $c = iconv('UCS-2', 'UTF-8', $c);
                $name .= $c;
            }else{
                $name .= $str;
            }
        }
    }

    return $name;
}

</code></code>
Copy after login

PS: 文件保存编码为utf-8.

转换函数取自于: PHP中对汉字进行UNICODE编码和解码的实现

这不是乱码,取出来直接放页面就行

这个不是乱码,是 unicode 编码,PHP 5.4 之后可以直接使用 JSON_UNESCAPED_UNICODE:

<code>$json = json_encode('中文', JSON_UNESCAPED_UNICODE);
</code>
Copy after login

被编码了,解码

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template