The cookie stores Chinese information

 

 When storing Chinese in cookies, sometimes there is a problem of 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 two functions:

escape(string) : Encode the string.

unescape(string) : Decode the string.

The code example is as follows:

var cookie = {
    set:function(key,val,time){//Set cookie method
        var date=new Date(); //Get the current time
        var expiresDays=time; //Set date to the time after n days
        date.setTime(date.getTime()+expiresDays*24*3600*1000); //Formatted as the time recognized by the cookie
        document.cookie=key + "=" + escape(val) +";expires="+date.toGMTString();  //设置cookie
    },
    get:function(key){//Get cookie method
        /* Get cookie parameters */
        var getCookie = document.cookie.replace(/[ ]/g,""); //Get the cookie, and format the obtained cookie to remove space characters
        var arrCookie = getCookie.split(";") //The obtained cookie is identified by "semicolon" and the cookie is saved in the array of arrCookie
        var tips; //declare variable tips
        for(var i=0;i<arrCookie.length;i++){ //Use the for loop to find the tips variable in the cookie
            var arr=arrCookie[i].split("="); //Identifies a single cookie with an "equal sign" and saves a single cookie as an arr array
            if(key==arr[0]){ //Match the variable name, where arr[0] refers to the cookie name, if the variable is tips, execute the assignment operation in the judgment statement
                tips=arr[1]; //Assign the value of the cookie to the variable tips
                break; // Terminate the for loop traversal
            }
        }
        return unescape(tips);
    }
}

 It is used as follows:

cookie.set('key','value, Chinese can also be',30) //Invalid after 30 days

cookie.get('key') // value, Chinese can also

 Original link: http://www.maoyupeng.com/use-cookie-on-javascript.html

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327075930&siteId=291194637