Jquery. Cookie usage

  • 2020-03-30 00:58:18
  • OfStack

Cookies are generated on the server side and sent to the user-agent (usually the browser). The browser will save the key/value of the Cookie to a text file in a directory and send the Cookie to the server the next time it requests the same website (provided the browser is set to enable cookies).

For example, a shopping site stores a list of products that the user has viewed, or a portal remembers which types of news the user prefers to view. Can you also store the user's login information with the user's permission, so that the user doesn't have to type it every time they visit the site?

How do you manipulate cookies in js/jquery? Today share a cookie operation class -jQuery.Cookie. Js, is a lightweight cookie management plug-in.

Cookie download address: (link: http://plugins.jquery.com/project/cookie).

Special note: a special error was found today, Google browser prompt: has no method $.cookie. $. Cookie is not a function; After debugging for half a day, I finally found the reason that if the same page is introduced twice or more Jquery plug-in will report this error.


1. Introduce jQuery and jQuery.Cookie. Js plug-in.

<script src="jQuery.1.8.3.js" type="text/javascript"></script>
<script src="jquery.cookie.js" type="text/javascript"></script>

2. Write the cookie to a file

 var COOKIE_NAME = 'username';  
  if( $.cookie(COOKIE_NAME) ){  
    $("#username").val( $.cookie(COOKIE_NAME) );  
      $.cookie(COOKIE_NAME, $("#username").val() , { path: '/', expires: 10 });  
      //var date = new Date();  
      //date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000)); // It expires three days later at this time   
      //$.cookie(COOKIE_NAME, $("#username").val(), { path: '/', expires: date });  
      $.cookie(COOKIE_NAME, null, { path: '/' }); //Delete the cookie


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

(1) read the cookie value

CookieName: the name of the cookie to read.

Example: $. Cookies (" username "); Read the value of the username stored in the cookie named.

(2) write the setting Cookie value:

$. Cookies (cookieName cookieValue); CookieName: the cookie name to set. CookieValue represents the corresponding value.

Example: $. Cookies (" username ", "admin"); Write the value "admin" to a cookie named username.

$. Cookies (" username ", NULL); Destroy the cookie named username

(3) parameter description of [option] :

Expires: finite date, which can be an integer or a date (in days). Note also that if you don't set this, the cookie will not work when the browser is closed

Path: the path where the cookie value is saved, by default, is the same as the page creation path.

Domin: cookie domain name property, which by default is the same as the page domain name. This is where you have to be very careful, the cross-domain concept, if you want the primary domain and the secondary domain to be valid you have to set ".xxx.com"

Secrue: a Boolean value that indicates whether a security protocol is needed to transfer cookie values.


$.cookie("like", $(":radio[checked]").val(), {
          path: "/", expiress: 7

A complete page code for setting and reading cookies:

<html xmlns="http://www.w3.org/1999/xhtml"> 
  <title>jQuery learning 2</title> 
  <script src="jQuery.1.8.3.js" type="text/javascript"></script> 
  <script src="jquery.cookie.js" type="text/javascript"></script> 
  <script type="text/javascript"> 
    $(function () { 
      if ($.cookie("like") == " Andy lau ") { 
        $(":radio[value=' Andy lau ']").attr("checked", 'checked') 
      else { 
        $(":radio[value=' Jacky cheung ']").attr("checked", 'checked') 
      $(":button").click(function () { 
        $.cookie("username", $("#username").val(), { 
          path: "/", expires: 7 
        $.cookie("like", $(":radio[checked]").val(), { 
          path: "/", expiress: 7 
  <p><input type="text" id="username" value="" /></p> 
    <input type="radio" name="like" value=" Andy lau " /> Andy lau  
    <input type="radio" name="like" value=" Jacky cheung " /> Jacky cheung  
  <p><input type="button" value=" save " /></p> 

The cookie is essentially a TXT text, so it can only be stored as a string. The object can only be stored as a cookie after it is serialized, and the object can only be retrieved after it is de-sequenced.

$(function () { 
     if ($.cookie("o") == null) { 
       var o = { name: " Zhang SAN ", age: 24 }; 
       var str = JSON.stringify(o);  //Serialize the pair into a string and store the cookie
       $.cookie("o", str, { 
         expires:7  //Set the time. If left blank, the browser closes the cookie.
       alert("cookie Is empty "); 
     else { 
       var str1 = $.cookie("o"); 
       var o1 = JSON.parse(str1);  //Characters are deserialized into objects
       alert(o1.name);        //Type the name value of the deserialized object

A lightweight cookie plug-in, can read, write, delete cookies.

Jquery. Cookies. Js configuration

The library file for jQuery is included first, followed by the library file for jQuery. Cookie. Js

< Script type = "text/javascript" SRC = "js/jquery - 1.6.2. Min. Js" > < / script>
< Script type = "text/javascript" SRC = "js/jquery. Cookies. Js" > < / script>

Method of use

Add a new session cookie:

$. Cookies (' the_cookie ', 'the_value');

Note: when the cookie is not specified, the cookie created will be valid until the user closes the browser by default, so it is called "session cookie".

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

$. Cookies (' the_cookie ', 'the_value, {expires, 7});

Note: the cookie created when the valid time of the cookie is specified is called a "persistent cookie".

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

$. Cookies (' the_cookie ', 'the_value' {expires: 7, path: '/'});

Note: by default, the cookie can only be read by the web page where the cookie is set. If you want a page to read a cookie set by another page, you must set the path to the cookie.

The path to the cookie is used to set the top-level directory that can read the cookie. Setting this path to the root of the site allows all pages to read cookies from each other (this is not usually done to prevent collisions)

Read the cookies:

$. Cookies (' the_cookie ');

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

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

$. Cookies (' the_cookie, null);

Interpretation of related parameters

Expires: 365

Define the valid time of a cookie, which can be a value (in days from the time the cookie was created) or a Date.

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

Path: '/'

Default: the cookie can only be read by the web page where the cookie is set.

Defines a valid path to a cookie. By default, the value of this parameter is the path of the web page where the cookie was created (the behavior of a 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 with a valid path, you need to include this path when calling the function :$.cookie('the_cookie', null, {path: '/'}); .

'example.com' domain.

Default: the domain name of the web page where the cookie is created.

Secure: true,

The default value is false. If true, the transmission of the cookie needs to use the secure protocol (HTTPS).

Raw: true,

The default value is false. By default, cookies are automatically encoded and decoded when read and written (encodeURIComponent encoding, decodeURIComponent decoding).

To turn this off set raw: true.

$. Cookies (' the_cookie '); // get cookie $. Cookie ('the_cookie', 'the_value'); // set cookie $. Cookie ('the_cookie', 'the_value', {expires: 7}); // set cookie with an expiration date seven days in the future $. Cookie ('the_cookie', '', {expires: -1}); / / delete the cookie
$. Cookies (' the_cookie, null); / / delete the cookie

Cookie ('the_cookie','the_value', {expires: 7, path: '/', domain:'80tvb.com', secure: true}); // full invocation mode

// or: $.cookie('the_cookie','the_value');

// delete Cookie: $. Cookie ('the_cookie',null);


JQuery operation cookie plug-in, the general use method is as follows

$. Cookies (' the_cookie '); // read the Cookie value
$. Cookies (' the_cookie ', 'the_value'); // sets the value of the cookie
Cookie ('the_cookie', 'the_value', {expires: 7, path:' /', domain: 'jquery.com', secure: true}); // create a new cookie including valid path domain name, etc
$. Cookies (' the_cookie ', 'the_value'); / / new cookies
$. Cookies (' the_cookie, null); // delete a cookie

Jquery sets cookie expiration time and checks whether cookies are available

Allow cookies to 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 whether cookies are available
$(document).ready(function() {var dt = new date(); Dt. Setseconds (dt) getseconds + 60 ()); Document. The cookie = "cookietest = 1; Expires = "+ dt. The togmtstring (); Var cookiesenabled = document.cookie.indexof(" cookietest= ")! = 1; If (! Cookiesenabled){//cookies cannot be used... . }});  

Related articles: