Detailed description of Cookie operations (setting, reading, and deleting) using javascript, and javascriptcookie
Cookie is a way for the client to store data and can be used for status persistence.
1. Set Cookie:
A. No expiration time: (if no expiration time is set, the default session-level Cookie will expire if the browser is closed)
Copy codeThe Code is as follows:
Function setCookie (name, value ){
Document. cookie = name + '=' + escape (value );
}
B. fixed expiration time:
Copy codeThe Code is as follows:
Function setCookie (name, value)
{
Var Days = 30;
Var exp = new Date ();
Exp. setTime (exp. getTime () + Days x 24x60*60*1000 );
Document. cookie = name + "=" + escape (value) + "; expires =" + exp. toGMTString ();
}
C. Custom expiration time:
Copy codeThe Code is as follows:
// Set the custom expiration time cookie
Function setCookie (name, value, time)
{
Var msec = getMsec (time); // get millisecond
Var exp = new Date ();
Exp. setTime (exp. getTime () + msec * 1 );
Document. cookie = name + "=" + escape (value) + "; expires =" + exp. toGMTString ();
}
// Converts string time to millisecond, 1 second = 1000 milliseconds
Function getMsec (DateStr)
{
Var timeNum = str. substring (0, str. length-1) * 1; // time quantity
Var timeStr = str. substring (str. length-1, str. length); // time unit prefix. For example, h indicates the hour.
If (timeStr = "s") // 20 s indicates 20 seconds
{
Return timeNum * 1000;
}
Else if (timeStr = "h") // 12 h indicates 12 hours
{
Return timeNum * 60x60*1000;
}
Else if (timeStr = "d ")
{
Return timeNum * 24*60*60*1000; // 30d indicates 30 days
}
}
2. Read Cookie:
Copy codeThe Code is as follows:
Function getCookie (name)
{
Var arr, reg = new RegExp ("(^ |)" + name + "= ([^;] *) (; | $)"); // Regular Expression matching
If (arr = document. cookie. match (reg )){
Return unescape (arr [2]);
}
Else {
Return null;
}
}
3. delete a Cookie:
Copy codeThe Code is as follows:
Function delCookie (name)
{
Var exp = new Date ();
Exp. setTime (exp. getTime ()-1 );
Var cval = getCookie (name );
If (cval! = Null ){
Document. cookie = name + "=" + cval + "; expires =" + exp. toGMTString ();
}
}
4. Call example:
Copy codeThe Code is as follows:
SetCookie ("name", "hayden ");
Alert (getCookie ("name "));
The above is all about the javascript operation cookie in this article. I hope it will help you learn javascript.