Summary of JS methods for creating and storing cookies

Source: Internet
Author: User
Tags hasownproperty

In js, cookie operations are related to the storage and clearing time. We only need to set the cookie expiration time to control its storage, below I will summarize some tips for using cookies in js.

Create and store cookies


In this example, we will create a cookie that stores the visitor's name. When visitors access the website for the first time, they are asked to enter their names. The name is stored in the cookie. When a visitor visits the website again, they will receive a welcome word.

First, we will create a function that stores the visitor's name in the cookie variable:

The Code is as follows: Copy code

Function Setcookie (name, value)

{

// Set the Cookie with the name and value
Var expdate = new Date (); // initialization time
Expdate. setTime (expdate. getTime () + 30*60*1000); // time
Document. cookie = name + "=" + value + "; expires =" + expdate. toGMTString () + "; path = /";

// That is, document. cookie = name + "=" + value + "; path =/"; time is optional, but the path (path) must be filled in, because the default path of JS is the current page, if this parameter is not specified, this cookie takes effect only on the current page! ~
}


The parameters in the above function contain the cookie name, value, and Expiration days.

In the above function, we first convert the number of days to a valid date, and then store the cookie name, value, and expiration date to the document. cookie object.

Then, we will create another function to check whether the cookie has been set:

The 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 whether the document. cookie object contains a cookie. If the document. cookie object contains certain cookies, it will continue to check whether the specified cookie is saved. If the cookie is found, the return value is returned. Otherwise, an empty string is returned.

Finally, we need to create a function. The function is used to display the welcome word if the cookie has been set. Otherwise, a prompt box is displayed asking you 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">
<Html xmlns = "http://www.w3.org/5o/xhtml">
<Head>
<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>
</Head>
<Body onLoad = "checkCookie ()">

</Body>
</Html>


We have discussed how to create a cookie.Cookie-saving browsing record instance

View records are read from cookies and parsed into json to generate html elements. Because the user may open several pages at the same time, there may be browsing records on these pages, In order to refresh the page every second even if the browsing records are displayed.
Two js files, history. js, and key chat records are used to save and read code. Json. js to process json.

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 );
}
// Display historical records
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 a 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 ('lil ');
Li. appendChild ();
Document. getElementById (pid). appendChild (li );
}
// Add cookie
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;
}
// Obtain the cookie
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],/ig ,''). replace (/,}/g ,'}'). replace (/,]/g, ']'). slice (0,-1 );
},
Push: function (sName, sValue ){
This. self [sName] = sValue;
This [sName] = sValue;
}
}

Html document

The 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>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.