Example of how JS adds a Cookie to retrieve the cookie value and deletes the cookie: jscookie
Cookie is a very useful function that can judge a certain state and the usage in the project is extremely high.
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 ();
Var strsec = getsec (time );
Var exp = new Date ();
Exp. setTime (exp. getTime () + strsec * 1 );
Document. cookie = name + "=" + escape (value) + "; expires =" + exp. toGMTString ();
}
// Read cookies
Function getCookie (name)
{
Var arr, reg = new RegExp ("(^ |)" + name + "= ([^;] *) (; | $ )");
If (arr = document. cookie. match (reg ))
Return (unescape (arr [2]);
Else
Return null;
}
// Delete cookies
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 ();
}
How does JS delete a cookie?
Js reads the cookie, js adds the cookie, and js deletes the cookie. The following is an example:
<! Doctype html public "-// W3C // dtd html 4.01 // EN" "www.w3.org/TR/html4/strict.dtd">
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = GB2312"/>
<Title> cookie processing function exercise (I wrote it, not what I think: Improving object-oriented) </title>
<Script language = "JavaScript" type = "text/javascript">
Function addCookie (objName, objValue, objHours) {// Add cookie
Var str = objName + "=" + escape (objValue );
If (objHours> 0) {// when the value is 0, no expiration time is set. When the browser is disabled, the cookie disappears automatically.
Var date = new Date ();
Var MS = objHours x 3600*1000;
Date. setTime (date. getTime () + MS );
Str + = "; expires =" + date. toGMTString ();
}
Document. cookie = str;
Alert ("cookie added successfully ");
}
Function getCookie (objName) {// obtain the cookie value of the specified name
Var arrStr = document. cookie. split (";");
For (var I = 0; I <arrStr. length; I ++ ){
Var temp = arrStr [I]. split ("= ");
If (temp [0] = objName) return unescape (temp [1]);
}
}
Function delCookie (name) {// to delete a cookie with the specified name, you can set its expiration time to a previous time.
Var date = new Date ();
Date. setTime (date. getTime ()-10000 );
Document. cookie = name + "= a; expires =" + date. toGMTString ();
}
Function allCookie () {// read all saved cooki... the remaining full text>
Js cookie deletion Error
Js reads the cookie, js adds the cookie, js deletes the cookie, and 5007-08-23 60: 07 shows 8 for example below m: <! Doctype html public "-.. W1C .. Dtd html 6. 08 .. EN ">