Creating and storing cookies
In this example we want to create a cookie that stores the visitor's name. When visitors visit the site for the first time, they are asked to fill in their names. The name is stored in the cookie. When visitors visit the site again, they receive a welcome word.
First, we'll create a function that stores the visitor's name in the cookie variable:
The code is as follows |
Copy Code |
function Setcookie (name, value) { To set a cookie with the name named and value var expdate = new Date (); Initialization time Expdate.settime (Expdate.gettime () + 30 * 60 * 1000); Time Document.cookie = name+ "=" +value+ "expires=" +expdate.togmtstring () + ";p ath=/"; namely document.cookie= name+ "=" +value+ ";p ath=/"; Time can not, but path (path) must be filled out, because the default path JS is the current page, if not filled, this cookie only on the current page in effect! ~ } |
The parameters in the above function hold the name, value, and expiration days of the cookie.
In the above function, we first convert the number of days to a valid date, and then we save the cookie name, value, and its expiration date to the Document.cookie object.
After that, we'll create another function to check if the cookie is set:
code is as follows |
copy code |
function GetCookie (c_name) { if (document.cookie.length>0) { C_start=document.cookie.indexof ( C_name + "=") if (c_start!=-1) { C_start=c_start + c_name.length +1 c_end=document.cookie.indexof (";", C_start) if (c_end==-1) c_end= Document.cookie.length return unescape (document.cookie.substring (c_start,c_end)) } } Return " } |
The above function first checks to see if a cookie exists in the Document.cookie object. If the Document.cookie object has certain cookies, it will continue to check that our specified cookie is stored. If we find the cookie we want, we return the value, otherwise we return an empty string.
Finally, we're going to create a function that, if the cookie is set, displays the welcome word, otherwise a prompt box is displayed to require the user to enter a name.
The code is as follows |
Copy Code |
function Checkcookie () { Username=getcookie (' username ') if (username!=null && username!= "") {alert (' Welcome again ' +username+ ')} Else { Username=prompt (' Please enter your name: ', "") if (username!=null && username!= "") { Setcookie (' username ', username,365) } } } |
A complete instance
The code is as follows |
Copy Code |
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <meta http-equiv= "Content-type" content= "text/html; Charset=utf-8″/> <title> Untitled Document </title> <script type= "Text/javascript" > function GetCookie (c_name) { if (document.cookie.length>0) { C_start=document.cookie.indexof (c_name + "=") if (c_start!=-1) { C_start=c_start + c_name.length+1 C_end=document.cookie.indexof (";", C_start) if (c_end==-1) c_end=document.cookie.length Return unescape (document.cookie.substring (c_start,c_end)) } } Return "" } function Setcookie (c_name,value,expiredays) { var exdate=new Date () Exdate.setdate (Exdate.getdate () +expiredays) document.cookie=c_name+ "=" +escape (value) + ((expiredays==null)? "": "Expires=" +exdate.togmtstring ()) } function Checkcookie () { Username=getcookie (' username ') if (username!=null && username!= "") {alert (' Welcome again ' +username+ ')} Else { Username=prompt (' Please enter your name: ', "") if (username!=null && username!= "") { Setcookie (' username ', username,365) } } } </script> <body onload= "Checkcookie ()" > </body>
|
It's about the creation of cookies. Let's take a look at a cookie. To save a browsing record instance
The display of the browsing record is read from the cookie and parsed into JSON to generate the HTML element. Because users may have several pages open at the same time, there may be a browse record on each of these pages, in order to refresh it once per second even if the browsing record is displayed.
To use 2 JS files, history.js, key chat records to save and read code. Json.js, the JSON is processed.
History.js
The code is as follows |
Copy Code |
var addhistory=function (Num,id) { Stringcookie=getcookie (' history '); var stringhistory= ""!=stringcookie?stringcookie: "{history:[]}"; var json=new json (stringhistory); var e= "{num:" +num+ ", ID:" +id+ "}"; json[' History '].push (e);//Add a new record Setcookie (' History ', json.tostring (), 30); } Show History var displayhistory=function () { var P_ele=document.getelementbyid (' history '); while (P_ele.firstchild) { P_ele.removechild (P_ele.firstchild); } var Historyjson=getcookie (' history '); var json=new json (Historyjson); var displaynum=6; For (i=json[' history '].length-1;i>0;i--) { Addli (json[' history '][i][' num '],json[' history '][i][' ID '), "history"); displaynum--; if (displaynum==0) {break;} } } Add an LI element var addli=function (num,id,pid) { var a=document.createelement (' a '); var href= ' product.action?pid= ' +id; A.setattribute (' href ', href); var t=document.createtextnode (num); A.appendchild (t); var li=document.createelement (' Li '); Li.appendchild (a); document.getElementById (PID). appendchild (LI); } Add cookies var setcookie=function (c_name,value,expiredays) { var exdate=new Date () Exdate.setdate (Exdate.getdate () +expiredays) cookieval=c_name+ "=" +escape (value) + ((expiredays==null)? "": "; expires=" +exdate.togmtstring ()); alert (cookieval); Document.cookie=cookieval; } Get cookies function GetCookie (c_name) { if (document.cookie.length>0) { C_start=document.cookie.indexof (c_name + "=") if (c_start!=-1) { C_start=c_start + c_name.length+1 C_end=document.cookie.indexof (";", C_start) if (c_end==-1) c_end=document.cookie.length document.write (document.cookie.substring (c_start,c_end) + "<br>"); Return unescape (document.cookie.substring (c_start,c_end)) } } Return "" } |
JSON file
The code is as follows |
Copy Code |
Json.js var JSON = function (Sjson) { This.objtype = (typeof Sjson); This.self = []; (function (S,o) {for (var i in O) {o.hasownproperty (i) && (S[i]=o[i],s.self[i]=o[i])}) (This, (this.objtype== ' string ')? Eval (' 0, ' +sjson): Sjson); } Json.prototype = { Tostring:function () { return this.getstring (); }, Valueof:function () { return this.getstring (); }, Getstring:function () { var sA = []; (function (o) { var oo = null; Sa.push (' {'); for (var i in O) { if (O.hasownproperty (i) && i!= ' prototype ') { OO = o[i]; if (oo instanceof Array) { Sa.push (i+ ': ['); for (var b in Oo) { if (Oo.hasownproperty (b) && b!= ' prototype ') { Sa.push (oo[b]+ ', '); if (typeof oo[b]== ' object ') Arguments.callee (oo[b)); } } Sa.push ('], '); Continue }else{ Sa.push (i+ ': ' +oo+ ', '); } if (typeof oo== ' object ') Arguments.callee (OO); } } Sa.push ('}, '); }) (this.self); Return Sa.slice (0). Join ('). Replace (/[object object],/ig, '). Replace (/,}/g, '} '). Replace (/,]/g, '] "). Slice (0,-1); }, Push:function (Sname,svalue) { This.self[sname] = svalue; This[sname] = svalue; } } |
HTML Document
code is as follows |
copy code |
Sample program <script type= "Text/javascript" src= ". /js/json.js "></script> <script type=" Text/javascript "src=". /js/history.js "></script> <ul id=" History " </ul> <script> AddHistory ( 15810782304,2); AddHistory (64654665,2); AddHistory (6843212,2); AddHistory (84984432521,2); SetInterval ("Displayhistory ()", 1000); </script> |