彻底解决JavaScript读取asp,PHP Cookie中文值乱码的问题

红色字体为使用方法:

asp页面使用:

<%   
'编码程序:       
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) to 0 step -1     
  strRtn=strRtn & chrw(cint(strArr(i)))     
 next     
 
 DecodeCookie=strRtn     
end function     
%>

<%
'使用
response.Cookies("username")=CodeCookie("lee is a man!@哈哈")
Response.Cookies("username").Expires = now()+3600
response.Write(DecodeCookie(request.Cookies("username")))
%>

==================================

js使用:

 

<SCRIPT   LANGUAGE=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;     
  }     
  //-->   
 
//设置cookies
function   SetCookie(name,value,expires)     
{     
 var   exp=new   Date();     
   exp.setTime(exp.getTime()+expires*60*1000);     
   documents.cookie=name+"="+escape(CodeCookie(value))+";expires="+exp.toGMTString()+";path=/";     
}     
//读取cookies
function   GetCookie(name)     
{     
 var   strArg=name+"=";     
  var   nArgLen=strArg.length;     
  var   nCookieLen=document.cookie.length;     
  var   nEnd;     
  var   i=0;     
  var   j;     

 while   (i<nCookieLen)     
 {     
  j=i+nArgLen;     
   if   (document.cookie.substring(i,j)==strArg)     
  {     
   nEnd=document.cookie.indexOf   (";",j);     
    if   (nEnd==-1)   nEnd=document.cookie.length;     
    return   DecodeCookie(unescape(document.cookie.substring(j,nEnd)));     
  }     
   i=document.cookie.indexOf("   ",i)+1;     
   if   (i==0)   break;     
 }     
  return   null;     
}
 
  </script> 
<script>
$(function(){
 alert(GetCookie("username"));
});
</script>

posted on 2010-12-26 17:54  woshilee  阅读(194)  评论(0)    收藏  举报

导航