JS Settings Cookie:
Suppose you want to save the value of the variable username ("Jack") in the a page to the cookie, the key value is name, then the corresponding JS code is:
Document.cookie= "Name=" +username;
JS Read Cookie:
Assume that the content stored in the cookie is: name=jack;password=123
The JS code that gets the value of the variable username in the B page is as follows:
var username=document.cookie.split (";") [0].split ("=") [1];
//js how to operate cookies!
//write Cookies
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 ();
}
//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 ();
}
Using the example
Setcookie ("name", "Hayden");
Alert (GetCookie ("name"));
If you need to set a custom expiration time
Then replace the above Setcookie function with the following two functions OK;
Program code
function Setcookie (name,value,time)
{
var strsec = getsec (time);
var exp = new Date ();
Exp.settime (Exp.gettime () + strsec*1);
Document.cookie = name + "=" + Escape (value) + "; expires=" + exp.togmtstring ();
}
function Getsec (str)
{
alert (str);
var str1=str.substring (1,str.length) * *;
var str2=str.substring (0,1);
if (str2== "s")
{
return str1*1000;
}
else if (str2== "H")
{
return str1*60*60*1000;
}
else if (str2== "D")
{
return str1*24*60*60*1000;
}
}
This is an example of using a set expiration time:
S20 is represented for 20 seconds
H refers to the hour, such as 12 hours: H12
D is the number of days, 30 days: D30
Setcookie ("name", "Hayden", "S20");
Use JS to set cookies, read cookies, delete Cookiev