Ajax跟PHP交互时编码问题的总结
2008-10-18 17:44 Jaypei 阅读(237) 评论(0) 编辑 收藏 举报JQuery使用Ajax传递参数给PHP页面的时候,在不做什么处理的情况下IE和FireFox中总有一个传递中文会乱码,是因为默认Ajax不统一的问题,网上找到一个有效的解决方法如下:
JS中使用escape()对中文字符串编码,PHP中用下面这个unescape()函数做处理:
function unescape($str,$charcode){
$text = preg_replace_callback("/%u[0-9A-Za-z]{4}/",toUtf8,$str);
return mb_convert_encoding($text, $charcode, 'utf-8');
}
function toUtf8($ar){
foreach($ar as $val){
$val = intval(substr($val,2),16);
if($val < 0x7F){ // 0000-007F
$c .= chr($val);
}elseif($val < 0x800) { // 0080-0800
$c .= chr(0xC0 | ($val / 64));
$c .= chr(0x80 | ($val % 64));
}else{ // 0800-FFFF
$c .= chr(0xE0 | (($val / 64) / 64));
$c .= chr(0x80 | (($val / 64) % 64));
$c .= chr(0x80 | ($val % 64));
}
}
return $c;
}
$text = preg_replace_callback("/%u[0-9A-Za-z]{4}/",toUtf8,$str);
return mb_convert_encoding($text, $charcode, 'utf-8');
}
function toUtf8($ar){
foreach($ar as $val){
$val = intval(substr($val,2),16);
if($val < 0x7F){ // 0000-007F
$c .= chr($val);
}elseif($val < 0x800) { // 0080-0800
$c .= chr(0xC0 | ($val / 64));
$c .= chr(0x80 | ($val % 64));
}else{ // 0800-FFFF
$c .= chr(0xE0 | (($val / 64) / 64));
$c .= chr(0x80 | (($val / 64) % 64));
$c .= chr(0x80 | ($val % 64));
}
}
return $c;
}