Home > Web Front-end > JS Tutorial > cookie stores Chinese information

cookie stores Chinese information

巴扎黑
Release: 2016-12-19 14:22:37
Original
1802 people have browsed it

When storing Chinese characters in cookies, sometimes there will be problems with Chinese garbled characters. For example, when accessing in the IOS system, the data may not be successfully stored in the cookie due to Chinese garbled characters. The main way to solve the problem of garbled characters is to use 2 functions. :

escape(string): Encode the string.

unescape(string): Decode the string.

The code example is as follows:

var cookie = {
    set:function(key,val,time){//设置cookie方法
        var date=new Date(); //获取当前时间
        var expiresDays=time;  //将date设置为n天以后的时间
        date.setTime(date.getTime()+expiresDays*24*3600*1000); //格式化为cookie识别的时间
        document.cookie=key + "=" + escape(val) +";expires="+date.toGMTString();  //设置cookie
    },
    get:function(key){//获取cookie方法
        /*获取cookie参数*/
        var getCookie = document.cookie.replace(/[ ]/g,"");  //获取cookie,并且将获得的cookie格式化,去掉空格字符
        var arrCookie = getCookie.split(";")  //将获得的cookie以"分号"为标识 将cookie保存到arrCookie的数组中
        var tips;  //声明变量tips
        for(var i=0;i<arrCookie.length;i++){   //使用for循环查找cookie中的tips变量
            var arr=arrCookie[i].split("=");   //将单条cookie用"等号"为标识,将单条cookie保存为arr数组
            if(key==arr[0]){  //匹配变量名称,其中arr[0]是指的cookie名称,如果该条变量为tips则执行判断语句中的赋值操作
                tips=arr[1];   //将cookie的值赋给变量tips
                break;   //终止for循环遍历
            }
        }
        return unescape(tips);
    }
}
Copy after login

The usage method is as follows:

Js code

cookie.set(&#39;key&#39;,&#39;value,中文也可以的&#39;,30)  //30天后失效  
  
cookie.get(&#39;key&#39;)   // value,中文也可以的
Copy after login


Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template