Home >Web Front-end >JS Tutorial >Tutorial examples of javascript cookie manipulation
cookie
Cookies, sometimes also used in their plural form Cookies, refer to the data (usually encrypted) stored on the user's local terminal by some websites in order to identify the user's identity and perform session tracking. The specifications defined in RFC2109 and 2965 are both obsolete, and the latest replaced specification is RFC6265.
The role of cookies
The server can use the arbitrariness of the information contained in Cookies to filter and regularly maintain this information to determine the status in HTTP transmission. The most typical application of cookies is to determine whether a registered user has logged in to the website. The user may be prompted whether to retain user information the next time he enters the website to simplify the login procedure. These are the functions of cookies. Another important application is "shopping cart" processing. Users may choose different products on different pages of the same website within a period of time, and this information will be written to Cookies so that the information can be retrieved when making the final payment.
jsSet cookie
document.cookie="popped=yes"
jsGet cookie
##function get_cookie (Name) { var search = Name + "="//Query retrieved value var returnvalue = "";//Return value if (document.cookie.length > 0) { sd = document.cookie.indexOf(search); if (sd!= -1) { sd += search.length; End = document.cookie.indexOf(";", sd); if (end == -1) End = document.cookie.length; // Unescape () function can decode the string encoded by Escape ().
Returnvalue=unescape(document.cookie.substring(sd, end))
}
}
return returnvalue;
}
//Usage:
get_cookie("popped");
In order to delete a cookie, you can set its expiration time to a past time, for example:
var cookie = {
set:function(key,val,time){//Set cookie method
var date=new Date(); //Get the current time
var expiresDays=time; //Set date to a time n days later
Date.setTime(date.getTime()+expiresDays*24*3600*1000); //Format to the time recognized by the cookie
Document.cookie=key + "=" + val +";expires="+date.toGMTString(); //Set cookie },
Get:function(key){//Get cookie method
/*Get cookie parameters*/
var getCookie = document.cookie.replace(/[ ]/g,""); //Get the cookie and format the cookie to remove the space characters
var arrCookie = getCookie.split(";") //The obtained cookie will be identified by "semicolon" and save the cookie to the array of arrCookie
var tips; //Declare variable tips
for(var i=0;i
var date = new Date(); //Get the current time
date.setTime(date.getTime()-10000); / /Set the date to the past time
DOCUMENT.COOKIE = key + "= v; expires =" + date.togmtring (); // Set cookie
} Return tips;
}
}
alert(cookie .get("uesr"));//Get cookie
The above is the detailed content of Tutorial examples of javascript cookie manipulation. For more information, please follow other related articles on the PHP Chinese website!