The Chinese encoding problem when JS reads server cookies

Source: Internet
Author: User
Tags split

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>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.