PHP 中文 转UNICODE, JS 将UNICODE转为GBK

 首先是PHP下的中文转为UNICODE进行传递

    function str_utf8_unicode($name){  
        $name = iconv('GBK','UCS-2', $name);  
        $len  = strlen($name);  
        $str  = '';  
        for ($i = 0; $i < $len - 1; $i = $i + 2){  
            $c  = $name[$i];  
            $c2 = $name[$i + 1];  
            if (ord($c) > 0){   //两个字节的文字  
                $str .= '\u'.base_convert(ord($c), 10, 16).str_pad(base_convert(ord($c2), 10, 16), 2, 0, STR_PAD_LEFT);  
                //$str .= base_convert(ord($c), 10, 16).str_pad(base_convert(ord($c2), 10, 16), 2, 0, STR_PAD_LEFT);  
            } else {  
                $str .= '\u'.str_pad(base_convert(ord($c2), 10, 16), 4, 0, STR_PAD_LEFT);  
                //$str .= str_pad(base_convert(ord($c2), 10, 16), 4, 0, STR_PAD_LEFT);  
            }  
        }  
        //$str = strtoupper($str);//转换为大写
		$str =strtolower($str);//转换为小写
        return $str;  
    }  

调用实例:$result[$i]['docsubject'] = str_utf8_unicode($result[$i]['docsubject']);



然后是JS下的补充函数

   var GB2312UnicodeConverter = { 
    ToUnicode: function (str) {
      return escape(str).toLocaleLowerCase().replace(/%u/gi, '\\u');
      } 
    , ToGB2312: function (str) {
        return unescape(str.replace(/\\u/gi, '%u'));
      } 
  };

然后在转码调用

var zurl = "";
zurl = "read_id.php?id=" + zid;
   //alert("zurl is:"+zurl);
   

$.getJSON(zurl,function(data){  
            var $jsontip = $("#jsonTip");  
            var strHtml = "";//存储数据的变量  
            $jsontip.empty();//清空内容  
            $.each(data,function(infoIndex,info){  
                  strHtml += "ID:"+info["id"]+"
"; // strHtml += "标题:"+info["docsubject"]+"
"; strHtml += "标题:"+GB2312UnicodeConverter.ToGB2312(info["docsubject"])+"
";



你可能感兴趣的:(web杂)