Html code:Copy to ClipboardReference: [www.bkjia.com] <! Doctype html public "-// W3C // dtd html 4.01 // EN" "http://www.w3.org/TR/html4/strict.dtd">
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Title> JavaScript and Cookie (1) </title>
</Head>
<Body>
<Form name = "frm1" method = "post" onsubmit = "savecookie ()">
<P> CookieMessage: <input type = "text" name = "cookieInfo" size = "50"/> </p>
<P> Valid-time: <input type = "text" name = "time" size = "10" value = "30"/> Please input a integer. </p>
<Div style = "border: 1px solid # ccc;" id = "divInfo"> </div>
<P> <input type = "submit" name = "submit" value = "Submit">
<Input type = "reset" name = "reset" value = "Reset"/> </p>
<P> <input type = "button" onclick = "writeAllCookie ()" value = "writeAllCookie"/> </p>
<P> <input type = "text" name = "txtGetSpc"/> <input type = "button" value = "GetSpecificCookie" onclick = "getCk ()" </p>
</Form>
</Body>
</Html>
Js Code:
Copy to ClipboardReference: [www.bkjia.com] <script language = "JavaScript" type = "text/javascript">
/*
* Set a common Cookie function. name is a required parameter. Others are optional, so use conditional statements to determine.
* If no expiration time is set during Cookie setting, the Cookie is temporary and only available for this session.
*/
Function setcookie (name, value, expires, path, domain, secure ){
Var curcookie = name + "=" + encodeURI (value)
+ (Expires )? "; Expires =" + expires. toGMTString ():"")
+ (Path )? "; Path =" + path :"")
+ (Domain )? "; Domain =" + domain :"")
+ (Secure )? "; Secure ":"");
Document. cookie = curcookie;
}
// Write Cookie
Function savecookie (){
Var cookieInfo = document. frm1.cookieInfo. value;
Var time = document. frm1.time. value;
Var now = new Date ();
Now. setDate (now. getDate () + time );
Setcookie ("myCookie", cookieInfo, now );
Document. write (decodeURI (document. cookie ));
}
// Read all Cooke
Function writeAllCookie (){
Document. cookie = "name1 =" + encodeURI ("name 1 ");
Document. cookie = "name2 =" + encodeURI ("name 2 ");
Document. cookie = "name3 =" + encodeURI ("Name 3 ");
Var strInfo;
Var cookie = document. cookie. split (";");
For (var I = 0; I <cookie. length; I ++ ){
Var ck = cookie [I]. split ("= ");
Var cName = ck [0];
Var cValue = decodeURI (ck [1]);
StrInfo + = cName + "=" + cValue + "<br> ";
}
Document. getElementById ("divInfo"). innerHTML = strInfo;
}
/*
* Common functions for reading specific cookies
*/
Function getSpecificCookie (name ){
If (document. cookie. length> 0 ){
Start = document. cookie. indexOf (name + "= ");
If (start! =-1 ){
Start = start + name. length + 1;
End = document. cookie. indexOf (";", start );
If (end =-1 ){
End = document. cookie. length;
}
}
Return decodeURI (document. cookie. substring (start, end ));
}
Return "";
}
Function getCk (){
Name = document.frm1.txt GetSpc. value;
Alert (getSpecificCookie (name ));
}
</Script>
Source: http://www.cnblogs.com/zghlx/