Jquery.cookie Practical Usage Detailed analysis

Source: Internet
Author: User
Tags set cookie jquery library

Cookies are generated by the server and sent to User-agent (typically a browser), and the browser saves the key/value of the cookie to a text file in a directory, The next time you request the same Web site, the cookie is sent to the server (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 prefer to browse. With the user's permission, you can also store the user's login information so that users don't have to type this information every time they visit the site?

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

Cookie:http://plugins.jquery.com/project/cookie.

Special reminder, today found a special error, Google browser tip: Has no method $.cookie. Firefox tip: $.cookie is not a function; debugging for half a day, and finally find the reason, if the same page two or more times to introduce the jquery plugin will report this error.

How to use:

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

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

2. Writing a cookie to a file

?
1234567891011121314 var COOKIE_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)); //三天后的这个时候过期       //$.cookie(COOKIE_NAME, $("#username").val(), { path: ‘/‘, expires: date });     }else     $.cookie(COOKIE_NAME, null, { path: ‘/‘ }); //删除cookie      });

Function.

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

(1) Read Cookie value

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

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

(2) Write set cookie value:

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

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

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

(3) [option] parameter description:

Expires: A finite date, which can be an integer or a date (in days). This place should also note that if you do not set this thing, the cookie will expire after the browser is closed.

Path:cookie the path to the saved value, which is the same as creating the page path by default.

The Domin:cookie domain Name property, by default, is the same as creating a page domain name. This place should pay considerable attention to the concept of cross-domain, if you want the primary domain two domain name valid, you want to set the ". xxx.com"

Secrue: A Boolean value that indicates whether a security protocol is required when transferring cookie values.

Example:

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

A full set of page codes to read the cookie:

?
12345678910111213141516171819202122232425262728293031323334 "http://www.w3.org/1999/xhtml">   <title>jQuery学习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 () {       $("#username").val($.cookie("username"));       if ($.cookie("like") == "刘德华") {         $(":radio[value=‘刘德华‘]").attr("checked", ‘checked‘)       }       else {         $(":radio[value=‘张学友‘]").attr("checked", ‘checked‘)       }       $(":button").click(function () {         $.cookie("username", $("#username").val(), {           path: "/", expires: 7         })         $.cookie("like", $(":radio[checked]").val(), {           path: "/", expiress: 7         })       })     })   </script> <body>   <p><input type="text" id="username" value="" /></p>   <p>     <input type="radio" name="like" value="刘德华" />刘德华     <input type="radio" name="like" value="张学友" />张学友   </p>   <p><input type="button" value="保存" /></p> </body>

A cookie is essentially a txt literal, so it can only be stored in a string, the object is usually serialized before it can be stored in a cookie, and the object is deserialized before it can be obtained.

?
123456789101112131415 $(function () {      if ($.cookie("o") == null) {        var o = { name: "张三", age: 24 };        var str = JSON.stringify(o);  //对序列化成字符串然后存入cookie        $.cookie("o", str, {          expires:7  //设置时间,如果此处留空,则浏览器关闭此cookie就失效。        });        alert("cookie为空");      }      else {        var str1 = $.cookie("o");        var o1 = JSON.parse(str1);  //字符反序列化成对象        alert(o1.name);        //输反序列化出来的对象的姓名值      }    })

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

Configuration of the Jquery.cookie.js

First contains the jquery library file, followed by the library file containing the Jquery.cookie.js

<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 the cookie is not valid, the cookie is created by default until the user closes the browser, so it is referred to as a "session cookie"

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


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

Note: When a cookie is specified, the cookie created is referred to as a "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 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 to read cookies. Set this path to the root of your Web site so that all Web pages can read cookies to each other (typically not set up to prevent conflicts)


Read cookies:

$.cookie (' The_cookie ');

The existence of a cookie = ' 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

expires:365

Defines the effective 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 where the cookie is set can read the cookie.

Defines a valid path for the cookie. By default, the value of this parameter is the path to 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: ' example.com '

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

Secure:true

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

Raw:true

Default value: False. By default, the cookies are encoded and decoded automatically when they are read and written (using encodeURIComponent encoding, decodeuricomponent decoding).

To turn this feature off, Raw:true can be set.


$.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 days on the future $.cookie (' The_cookie ', ' ', {Expires:-1}); Delete Cookie
$.cookie (' The_cookie ', null); Delete Cookie


$.cookie (' The_cookie ', ' The_value ', {expires:7, path: '/', Domain: ' 80tvb.com ', secure:true});//Full call mode

or this: $.cookie (' The_cookie ', ' the_value ');

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

jquery operation Cookie Plug-in, probably using 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: ' jquery.com ', secure:true});//Create a new cookie including the validity path domain name, etc.
$.cookie (' The_cookie ', ' the_value '); New Cookie
$.cookie (' The_cookie ', null); Delete a cookie


jquery Set cookie expiration time and check whether cookies are available

Make 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 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 ...});

Jquery.cookie Practical Usage Detailed analysis

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.