AJAX返回中文乱码


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

这是什么编码?

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

编码 json php Ajax JavaScript

大哥hehe 9 years, 11 months ago

被编码了,解码

瓶中的小玲仙体 answered 9 years, 11 months ago

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


 $json = json_encode('中文', JSON_UNESCAPED_UNICODE);

棉布晾晒中 answered 9 years, 11 months ago

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

怠惰的喵老爷 answered 9 years, 11 months ago


 <?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;
}

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

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

huandi answered 9 years, 11 months ago

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


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

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

冰天百花塟 answered 9 years, 11 months ago

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

狂氣D紳士 answered 9 years, 11 months ago

Your Answer