The source of the problem is that cookies are encoded when they are passed.
An escape (hexadecimal encoding) is required before the cookie content is written and is encoded in bytes.
Any Chinese character will be split into two bytes encoded separately, and JS in the Read cookie, unescape again in byte unit decoding, so finally each Chinese characters have become two bytes of garbled. What do we do?
Do not worry on the server side, ASP or PHP can be read correctly, the script interpretation will deal with this problem.
After careful study, we found that as long as in the hexadecimal codec (codec) process can save Chinese character information, so we need to outsource a layer of codec process, the scheme is as follows:
1. Converts each character in the cookie string to a string of Unicode code (with a special character as the delimiter of the string) before escape coding.
2. After decoding the unescape, all the Unicode strings are extracted and then converted to the original character using the corresponding function.
<SCRIPT type="text/javascript">
<!--
//编码程序:
function CodeCookie(str)
{
var strRtn="";
for (var i=str.length-1;i>=0;i--)
{
strRtn+=str.charCodeAt(i);
if (i) strRtn+="a"; //用a作分隔符
}
return strRtn;
}
//解码程序:
function DecodeCookie(str)
{
var strArr;
var strRtn="";
strArr=str.split("a");
for (var i=strArr.length-1;i>=0;i--)
strRtn+=String.fromCharCode(eval(strArr[i]));
return strRtn;
}
//-->
</script>
The VBScript version of the program is as follows:
<SCRIPT LANGUAGE=vbscript>
<!--
"编码程序:
function CodeCookie(str)
Dim i
Dim strRtn
for i=len(str) to 1 step -1
strRtn=strRtn & ascw(mid(str,i,1))
if (i<>1) then strRtn = strRtn & "a" "用a作分隔符
next
CodeCookie=strRtn
end function
"解码程序:
function DecodeCookie(str)
Dim i
Dim strArr,strRtn
strArr=Split(str,"a");
for i=UBound(strArr)-LBound(strArr) to 1 step -1
strRtn=strRtn & chrw(Val(strArr(i)))
next
DecodeCookie=strRtn
end function
-->
</script>