JavaScript operation COOKIE instance code sharing

Source: Internet
Author: User

Cookies are commonly used in WEB development. They can be used not only in js, but also in php. Next I will introduce a cookie operation class to read cookies, delete operation.

Compared with javascript, it is easier to use backend php to operate cookies. Therefore, since javascript has rarely been used to operate cookies in the past, we have encountered some detours and shared them to avoid making the same mistakes as me.

The first point is that I know document. cookie returns a string consisting of all cookies. Therefore, when setting a cookie, I assume that the new cookie is spliced to the string and assigned to document. cookie.

This is not the case after testing. document. cookie = "; is to add or update a new cookie, such as document. cookie = "myck = yes;" adds a cookie named myck. If you want to add multiple cookies at the same time, document. cookie = "key1 = 1; key2 = 2. If you want to add the expiration time, storage domain and other information, simply add the relevant parameters. For example, document. cookie = 'myck = yes; expires = expire_time; domain = domain '.

This operation does not affect existing non-identical cookies.

Second, when setting the cookie expiration time, I mistakenly thought it would be enough to set a timestamp. The result was tested and tested. It was found that the cookie was not valid and the cookie validity period was always the session cycle. Later, we found that the standard string time format is used, similar to "Mon Jul 23 2012 20:08:10 GMT + 0800 GMT". 1343045321299 is invalid.


Cookie. js File

The Code is as follows: Copy code

Var COOKIE = (function (){

Var getDateString = function (offset ){

Var date = new Date ();

Date. setTime (+ date + offset * 1000 );

Return date. toGMTString ();

},

GetCookies = function (){

Var cookie = document. cookie | '',

Subs = cookie. split (/; s? /),

_ Subs, cks = {};

For (var I = 0; I <subs. length, subs [I]; I ++ ){

_ Subs = subs [I]. split ('= ')

Cks [unescape (_ subs [0])] = unescape (_ subs. slice (1). join ('= '));

}

Return cks;

}

 


Return {

Refresh: function (){

This. cookies = getCookies ();

Return this;

},

Has: function (key ){

Return this. cookies [key]! = Null;

},

Get: function (key ){

Return this. cookies [key];

},

Set: function (key, value, expire, path, domain, secure ){

Var myck = escape (key) + '=' + escape (value = null? '': Value );

If (! IsNaN (expire = parseFloat (expire )))

Myck + = '; expires =' + getDateString (expire );

If (path) myck + = '; path =' + path;

If (domain & domain! = Location. hostname) myck + = '; domain =' + domain;

If (secure) myck + = '; secure ';

Document. cookie = myck;

Return this. refresh (). has (key );

},

Remove: function (key, path, domain ){

Var paths = [],

Domains = [],

Arr, self = this;

If (path ){

Paths = [path];

} Else {

Arr = location. pathname. match (/.*? /|. + $/G );

This. each (arr, function (I ){

Var;

Paths. push (a = arr. slice (0, I + 1). join (''));

If (/[^/] +/$/. test ()){

Paths. push (a. slice (0,-1 ));

}

If (/[^/] $/. test ()){

Paths. push (a + '/');

}

});

}

 


If (domain ){

Domains = [domain];

} Else {

Arr = location. hostname. split ('.');

This. each (arr, function (I ){

Domains. push (arr. slice (-I). join ('.'));

});

Domains. push ('.' + domains [0]);

}

 


This. each (paths, function (){

Var path = this + '';

Self. each (domains, function (){

Self. set (key, '',-1000, path, this + '');

});

});

 


Return !! Path | !! Domain |! This. has (key );

},

Clear: function (path, domain ){

For (var key in this. cookies ){

This. remove (key, path, domain );

}

Return !! Path | !! Domain | function (){

For (var key in this. cookies ){

Return false;

}

Return true;

}. Call (this );

},

Each: function (arr, func ){

Var I = 0, j = arr. length;

For (; I <j; I ++ ){

If (func. call (arr [I], I) === false ){

Break;

}

}

}

}. Refresh ();

})();

// First introduce COOKIE. js in the page

The Code is as follows: Copy code

// Call
COOKIE. has (name); // checks whether there is a cookie named name.
COOKIE. set (key, value, expire, path, domain); // set a new cookie. true indicates that the setting is successful, and false indicates that the setting fails.
COOKIE. remove (name, path, domain); // delete a cookie named name. "true" indicates that the COOKIE is successfully deleted, and "false" indicates that the cookie fails to be deleted.
COOKIE. get (name); // get the cookie value named name
COOKIE. clear (path, domain); // clear all cookies

// Note: remove and clear methods. If path or domain is not set, cookies in all root domains, subdomains, and depth paths will be deleted.

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.