Cookie () usage detailed parsing __jquery

Source: Internet
Author: User
Tags set time set cookie

Cookies are generated by the server side and sent to User-agent (typically the browser), and the browser saves the cookie key/value to a text file in a directory. Send the cookie to the server the next time you request the same Web site (provided the browser is set to enable cookies).

For example, a shopping site stores a list of products that users have browsed, or a portal that remembers what kind of news users like to choose to browse. With the user's permission, you can also store the user's logon information so that users do not have to type the information each time they visit the site.

How to manipulate cookies in js/jquery. Today sharing a cookie operation class--jquery.cookie.js, is a lightweight cookie management plugin.

Cookie Download Address: Http://

Special reminder, today found a special error, Google browser tip: Has no method $.cookie. Firefox browser hint: $.cookie is not a function, debugging for a long time, finally found the reason, if the same page two or more times to introduce jquery Plug-ins will be reported this error.

How to use:

1, the introduction of jquery and JQuery.Cookie.js Plug-ins.

Copy code code as follows:
<script src= "Jquery.1.8.3.js" type= "Text/javascript" ></script>
<script src= "Jquery.cookie.js" type= "Text/javascript" ></script>

2. Write cookies to file?
Varcookie_name = ' username ';
if ($.cookie (Cookie_name)) {
$ ("#username"). Val ($.cookie (Cookie_name));
$ ("#check"). Click (function () {
if (this.checked) {
$.cookie (Cookie_name, $ ("#username"). Val (), {path: '/', expires:10});
var date = new Date ();
Date.settime (Date.gettime () + (3 * 24 * 60 * 60 * 1000)); Expires at this time after three days.
$.cookie (Cookie_name, $ ("#username"). Val (), {path: '/', expires:date});
$.cookie (Cookie_name,null, {path: '/'}); Delete Cookies


Syntax: $.cookie (name, value, [option])

(1) Read Cookie value

$.cookie (cookiename) CookieName: The name of the cookie to read.

Example: $.cookie ("username"); Read the value saved in the cookie named username.

(2) Write set cookie value:

$.cookie (Cookiename,cookievalue); CookieName: The name of the cookie to set, Cookievalue represents the corresponding value.

Example: $.cookie ("username", "admin"); The value ' Admin ' is written to a cookie named username.

$.cookie ("username", NULL); To destroy a cookie named username

(3) [option] parameter description:

Expires: finite date, can be an integer or a date (in days). This place should also be noted that if this thing is not set, the cookie will fail after the browser shuts down.

The path saved by the Path:cookie value, which is the default consistent with the Create page path.

Domin:cookie Domain Name property, the default is the same as creating a page domain name. This place should be quite aware of the concept of Cross-domain, if you want the primary domain name two-level domain name valid, set the "."

Secrue: A Boolean value that indicates whether a security protocol is required to transmit a cookie value.


Copy code code as follows:
$.cookie ("Like", $ (": radio[checked]"). Val (), {
Path: "/", expiress:7

A full set of page code to read cookies:

$ (function () {
if ($.cookie ("o") = = null) {
Varo = {name: "John", age:24};
Varstr = Json.stringify (o); To serialize to a string and then into a cookie
$.cookie ("O", str, {
Expires:7//Set time, if this is left blank, the browser will disable this cookie.
Alert ("Cookie is empty");
VARSTR1 = $.cookie ("O");
Varo1 = Json.parse (STR1); Character deserialization into an object
alert (; The name value of the object that is being deserialized


A cookie is essentially a txt text, so it can only be stored in a string, the object is usually serialized before it can be stored in the cookie, and the time to reverse the sequence to get the object.

$ (function () {
if ($.cookie ("o") = = null) {
Varo = {name: "John", age:24};
Varstr = Json.stringify (o); To serialize to a string and then into a cookie
$.cookie ("O", str, {
Expires:7//Set time, if this is left blank, the browser will disable this cookie.
Alert ("Cookie is empty");
VARSTR1 = $.cookie ("O");
Varo1 = Json.parse (STR1); Character deserialization into an object
alert (; The name value of the object that is being deserialized

A lightweight cookie plugin that can read, write, and delete cookies.

Configuration of Jquery.cookie.js

First contains a library file for jquery, followed by a jquery.cookie.js library file

<script type= "Text/javascript" src= "Js/jquery-1.6.2.min.js" ></script>
<script type= "Text/javascript" src= "Js/jquery.cookie.js" ></script>

How to use

Add a new session cookie:

$.cookie (' The_cookie ', ' the_value ');

Note: When a cookie is not valid, the creation of the cookie is not valid until the user closes the browser, so it is called "Session cookie"

Create a cookie and set the valid time to 7 days:

$.cookie (' The_cookie ', ' The_value ', {expires:7});

Note: When the cookie is valid, the cookie created is called the persistent cookie (persistent cookie).

Create a cookie and set a valid path for the cookie:

$.cookie (' The_cookie ', ' The_value ', {expires:7, path: '/'});

Note: By default, only the Web page that sets the cookie can read the cookie. If you want a page to read a cookie for another page setting, you must set the path of the cookie.

The path to the cookie is used to set up a top-level directory that can read cookies. Set this path to the root of the Web site so that all pages can read cookies to each other (do not generally set this up to prevent conflicts)

Read cookies:

$.cookie (' The_cookie ');

Cookies exist => ' the_value ' $.cookie (' not_existing '); Cookie does not exist => null

Delete the cookie by passing null as the value of the cookie:

$.cookie (' The_cookie ', null);

explanation of related parameters


Defines the valid time for a cookie, which can be one (from the time the cookie was created, in days), or a date.

If omitted, the cookie created is a session cookie that will be deleted when the user exits the browser.

Path: '/'

By default: Only the Web page that sets the cookie can read the cookie.

Defines a valid path for a cookie. By default, the value of this parameter is the path of the Web page where the cookie was created (the behavior of the standard browser).

If you want to access this cookie throughout the site, you need to set a valid path: path: '/'.

If you want to delete a cookie that defines a valid path, you need to include this path when calling the function: $.cookie (' The_cookie ', NULL, {path: '/'});.

Domain: ' '

Default value: The domain name of the Web page that created the cookie.


Default value: False. If the transport for True,cookie requires the use of security Protocol (HTTPS).


Default value: False. By default, encoding and decoding is done automatically when the cookie is read and written (using encodeURIComponent encoding, decodeuricomponent decoding).

To turn off this feature setting raw:true.

$.cookie (' The_cookie '); Get Cookie $.cookie (' The_cookie ', ' the_value '); Set Cookie $.cookie (' The_cookie ', ' The_value ', {expires:7}); Set cookie with a expiration date seven in the Future $.cookie (' The_cookie ', ', {Expires:-1}); Delete Cookie
$.cookie (' The_cookie ', null); Delete Cookie

$.cookie (' The_cookie ', ' The_value ', {expires:7, path: '/', Domain: ' ', secure:true});

Or so: $.cookie (' The_cookie ', ' the_value ');

Delete Cookie: $.cookie (' The_cookie ', null);

jquery Operation Cookie Plug-ins, the approximate use of the following methods

$.cookie (' The_cookie '); Read Cookie value
$.cookie (' The_cookie ', ' the_value '); Set the value of a cookie
$.cookie (' The_cookie ', ' The_value ', {expires:7, path: '/', Domain: ' ', secure:true});/create a new cookie including the expiration path domain name, etc.
$.cookie (' The_cookie ', ' the_value '); New Cookie
$.cookie (' The_cookie ', null); Delete a cookie

jquery Sets the cookie expiration date and checks whether cookies are available

let cookies expire in X minutes
var date = new Date ();
Date.settime (Date.gettime () + (x * 60 * 1000));
$.cookie (' Example ', ' foo ', {expires:date});

$.cookie (' Example ', ' foo ', {expires:7});

Check to see if cookies are available
$ (document). Ready (function () {var dt = new Date ();d t.setseconds (dt.getseconds () +);d Ocument.cookie = "cookietest=1; Expires= "+ dt.togmtstring (); var cookiesenabled = Document.cookie.indexof (" cookietest= ")!= -1;if (!cookiesenabled) {// Cookies cannot be used ...});

Turn from:


Cookies are a hard disk or memory that enables a Web server to store a small amount of data on a client. Or a technology that reads data from a client's hard disk. When you visit a website, you will produce a very small text file on your hard disk, which can record your user ID, password, browsed pages, The time of the stay and other information. When you come to the site again, the site by reading cookies, learn about your information, you can make the appropriate action, such as on the page to show you welcome the slogan, or let you do not enter the ID, password directly login and so on. In essence, it can be seen as your identity card.

The use of traditional JavaScript to set up and get cookies information is cumbersome, to write a few functions to deal with, fortunately, jquery helped us do a lot of things, with the help of the jquery cookie plugin, we can easily create, acquire and delete cookies. The JQuery cookie is a good cookie plugin, presumably using the following methods:

Write Cookie

$.cookie ("This-cookie", "This-value", {
    expires:10,//valid date
    path: "/",//cookie path
    domanin:    // The domain name
    of the cookie Secure:true//true,cookie transmission will require a security protocol, otherwise

Read cookies

$.cookie ("This-cookie")

Delete Cookies

$.cookie ("This-cookie", NULL)

is not very simple, this way you can complete cookies below to see a demo example

$ (function () {
            $ ("ul Li"). Click (function () {
                $ ("#" AddClass ("cur"). Siblings (). Removeclass ("cur") ; Toggles the selected style
                $ ("#colortable"). attr ("href", ". css");//replace the corresponding stylesheet
                $.cookie ("cookie",//write cookie each time)
                        that requires cookies to write {
                        "path": "/",//cookie default property
                        "Expires": 10/Valid days})
            var Cookie=$.cookie ("Cookie"); Reads the cookie
            if (cookie) {
                    $ ("#" +cookie). AddClass ("cur"). Siblings (). Removeclass ("cur");
                    $ ("#colortable"). attr ("href", cookie+ ". css");
                    $.cookie ("Cookie", cookie,{
                        "path": "/",


<li id= "colour_1" > Red </li>
<li id= "colour_2" > Black </li>

A simple skin-changing effect is coming out.

If using Google browser to open remember to be on the server side Oh.
The above demo to note that the place is:
The box that was clicked. Class or ID is the same as the corresponding stylesheet name.
This completes the pull.
After finishing the code

$ (function () {
            $ ("ul Li"). Click (function () {
                MyCookie (
            var Cookie=$.cookie ("Cookie"); Read Cookie
            if (cookie) {
                MyCookie (cookie);
        function MyCookie (Thiscookie) {
            $ ("#" +thiscookie). AddClass ("cur"). Siblings (). Removeclass ("cur");
            $ ("#colortable"). attr ("href", thiscookie+ ". css");
            $.cookie ("Cookie", thiscookie,{
                "path": "/",
Turn from:

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: 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.