HTML code:
Copy Code code as follows:
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01//en" "HTTP://WWW.W3.ORG/TR/HTML4/STRICT.DTD" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title>javascript and Cookies (i) </title>
<body>
<form name= "Frm1" method= "post" onsubmit= "Savecookie ()" >
<p>cookiemessage:<input type= "text" name= "Cookieinfo" size= "/></p>"
<p>valid-time:<input type= "text" name= "Time" size= "ten" value= ""/>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>
JS Code:
Copy Code code as follows:
<script language= "JavaScript" type= "Text/javascript" >
/*
* Set the common function of the cookie, where name is the required parameter. The other is optional, so use conditional statement to judge.
* The cookie is temporary if you set the cookie without setting an expiration time, only if this session is available
*/
function Setcookie (name, value, expires, path, domain, secure) {
var Curcookie = name + "=" + encodeURI (value)
+ ((expires)? "; expires=" + expires.togmtstring (): "")
+ (path)? ";p ath=" + Path: "")
+ (domain)? ";d omain=" + domain: "")
+ (Secure)? "; Secure": "");
Document.cookie = Curcookie;
}
Write a 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;
}
/*
* Read common functions for 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.txtGetSpc.value;
Alert (Getspecificcookie (name));
}
</script>