在PHP中先用escape函数编码,到客户端时利用js中的unescape解码。
escape函数如下:
function escape($str)
{
preg_match_all("/[\x80-\xff].|[\x01-\x7f]+/",$str,$r);
$ar = $r[0];
foreach($ar as $k=>$v)
{
if(ord($v[0]) < 128)
$ar[$k] = rawurlencode($v);
else
$ar[$k] = "%u".bin2hex(iconv("GB2312","UCS-2",$v));
}
return join("",$ar);
}
例子:test.php
<?php
function escape($str) {
preg_match_all("/[\x80-\xff].|[\x01-\x7f]+/",$str,$r);
$ar = $r[0];
foreach($ar as $k=>$v) {
if(ord($v[0]) < 128)
$ar[$k] = rawurlencode($v);
else
$ar[$k] = "%u".bin2hex(iconv("GB2312","UCS-2",$v));
}
return join("",$ar);
}
$name = escape("深圳人");
setcookie("name", $name);
?>
<scrīpt>
function get_cookie(name)
{
var result = null;
var myCookie = document.cookie + ";";
var searchName = name + "=";
var startOfCookie = myCookie.indexOf(searchName);
var endOfCookie;
if (startOfCookie != -1)
{
startOfCookie += searchName.length;
endOfCookie = myCookie.indexOf(";",startOfCookie);
result = unescape(myCookie.substring(startOfCookie, endOfCookie));
}
return result;
}
</scrīpt>
<scrīpt>
document.write("js:" + unescape(getCookie("name")));
</scrīpt>
另外还有一个方法:
在PHP5中,可以使用setrawcookie()函数来代替,它是在设置cookie值的时候没有编码的,所以在设置cookie的时候也不用先用escape函数编码,这时JS也能直接读取cookie的值