Cookies are a way for the client to store data and can be used to do state keeping.
1. Set Cookies:
A. No Expiration Time: (If the expiration time is not set, the default is session-level cookie, browser shutdown will be invalidated)
Copy Code code as follows:
function Setcookie (name,value) {
Document.cookie = name + ' = ' + escape (value);
}
B. Fixed expiration time:
Copy Code code as follows:
function Setcookie (name,value)
{
var days = 30;
var exp = new Date ();
Exp.settime (Exp.gettime () + days*24*60*60*1000);
Document.cookie = name + "=" + Escape (value) + "expires=" + exp.togmtstring ();
}
C. Custom Expiration Time:
Copy Code code as follows:
Set Custom Expiration Cookies
function Setcookie (name,value,time)
{
var msec = getmsec (time); Get milliseconds
var exp = new Date ();
Exp.settime (Exp.gettime () + msec*1);
Document.cookie = name + "=" + Escape (value) + "expires=" + exp.togmtstring ();
}
Converts a string time to milliseconds, 1 seconds =1000 milliseconds
function Getmsec (DATESTR)
{
var timenum=str.substring (0,str.length-1) *1; Amount of time
var timestr=str.substring (str.length-1,str.length); Time unit prefix, such as h for hours
if (timestr== "s")//20s represents 20 seconds
{
return timenum*1000;
}
else if (timestr== "H")//12h represents 12 hours
{
return timenum*60*60*1000;
}
else if (timestr== "D")
{
return timenum*24*60*60*1000; 30d means 30 days
}
}
2. Read cookies:
Copy Code code as follows:
function GetCookie (name)
{
var arr,reg=new RegExp ("(^|)" +name+ "= ([^;] *)(;|$)"); Regular match
if (Arr=document.cookie.match (reg)) {
Return unescape (arr[2]);
}
else{
return null;
}
}
3. Delete cookies:
Copy Code code 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 Code code as follows:
Setcookie ("name", "Hayden");
Alert (GetCookie ("name"));
This is the entire contents of this article about JavaScript manipulation cookies, and hopefully it will help you learn about JavaScript.