One 、jQuery.Cookie.js The plug-in is a lightweight Cookie Management plug-in .

Special reminder , I found a special mistake today ,google Browser prompt :has no method $.cookie. It's a tip from the Firefox browser :$.cookie is not a function; Debugging for half a day , Finally find out why , If the same page is introduced twice or more jQuery The plug-in will report this error .

Usage method :

1、 introduce jQuery And jQuery.Cookie.js plug-in unit .

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

2、 function .

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

(1) Read cookie value

$.cookie(cookieName) cookieName: To read the cookie name .

Example :$.cookie("username");  Read saved in cookie It's called username Value .

(2) Write settings Cookie value :

$.cookie(cookieName,cookieValue); cookieName: To set up cookie name ,cookieValue Represents the corresponding value .

Example :$.cookie("username","admin");  Will value "admin" write in cookie be known as username Of cookie in .

$.cookie("username",NULL); The destruction name is username Of cookie

(3) [option] Parameter description :

expires: Limited dates , It can be an integer or a date ( Company : God ). This place should also pay attention to , If you don't set this thing , After the browser is closed, this cookie Is failure

path: cookie The path to save the value , The default is the same as the creation page path .

domin:  cookie Domain name attributes , The default is the same as creating a page domain name . This place should be paid more attention to , Cross domain concept , If you want the primary domain name and secondary domain name to be valid, set ".xxx.com"

secrue: A Boolean value , Indicates transmission cookie When the value of , Whether a security protocol is needed .

Example :

 $.cookie("like", $(":radio[checked]").val(), {
path: "/", expiress: 7
})
A complete set and read cookie Page code for :
 
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Study 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") == " Lau Andy ") {
$(":radio[value=' Lau Andy ']").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
})
})
})
</script>
</head>
<body>
<p><input type="text" id="username" value="" /></p>
<p>
<input type="radio" name="like" value=" Lau Andy " /> Lau Andy
<input type="radio" name="like" value=" Jacky Cheung " /> Jacky Cheung
</p>
<p><input type="button" value=" preservation " /></p>
</body>
</html>
 
cookie It's essentially a txt Text , So you can only store strings , Objects usually need to be serialized before they can be stored in cookie, And when you take it, you have to reverse the sequence to get the object .
 
 

$(function () {
          if ($.cookie("o") == null) {
              var o = { name: " Zhang San ", age: 24 };
              var str = JSON.stringify(o); // To serialize into a string and store it in cookie
              $.cookie("o", str, {
                  expires:7   // Setup time , If left blank here , The browser closes this cookie Is the failure .
              });
              alert("cookie It's empty ");
          }
          else {
              var str1 = $.cookie("o");
              var o1 = JSON.parse(str1); // Characters are de sequenced into objects
              alert(o1.name); // Enter the name value of the deserialized object
          }
      })

------------------------------------------------------------------------------------------------

$(function () {

window.setTimeout(GetCookie, 1);
     });

// Reading and writing Cookie--------------------------------------
        // Login successful , Log in name ; Open login page , Read the last login
        // Write Cookie
        function SetCookie() {
            if ($.cookie("MyWebSite.Login") == undefined || $.cookie("MyWebSite.Login") == null) {
                var o = new Array(0);// { loginName: $('#userName').val() };
                o.push($('#userName').val());
                var str = JSON.stringify(o); // To serialize into a string and store it in cookie
                $.cookie("MyWebSite.Login", str, {
                    expires: 7   // Setup time , If left blank here , The browser closes this cookie Is the failure .( Company : God )
                });
            }
            else {
                var arr = $.cookie("MyWebSite.Login");
                arr = JSON.parse(arr);
                if (arr.indexOf($('#userName').val()) <= 0) {
                    arr.push($('#userName').val());

var strNew = JSON.stringify(arr); // To serialize into a string and store it in cookie
                    $.cookie("MyWebSite.Login", strNew, {
                        expires: 7   // Setup time , If left blank here , The browser closes this cookie Is the failure .( Company : God )
                    });
                }
            }
        }
        // read Cookie
        function GetCookie() {

var arr = $.cookie("MyWebSite.Login");
            if (arr == undefined) return;
            arr = JSON.parse(arr);
            if (arr.length > 0) {
                $('#userName').val(arr[arr.length - 1]);
                $('#pwd').focus().select();
            }
        }

//----------------------------------------------

jQuery Plug in Cookie More articles about

  1. jQuery Plug in Cookie How to use plug-ins ~

    One . Introduce 1-1.jQuery.Cookie.js The plug-in is a lightweight Cookie Management plug-in . Download address :jQuery-cookie.js  Friends in need , Right click to save as ! Two . Usage method 2-1. introduce jQu ...

  2. jQuery plug-in unit (cookie Store value )

    Use cookie After the plug-in , It's easy to pass through cookie Object preservation . Read . Delete user information , Also can pass the cookie The plug-in keeps the user's browsing history , Its calling format is : preservation :$.cookie(key,value): Read :$ ...

  3. jQuery Plug in settings cookie

    Yes cookies When you visit a website, you will be with us all the time , Recording our every move , And will not endanger the user's privacy information , Will be saved as , In this way, the user does not have to operate the repeated steps again , It's very convenient for customers , Also increased the customer to the website ...

  4. jQuery plug-in unit -- Cookie plug-in unit jquery.cookie.js( turn )

    Cookie It's a small text file placed on the client by the website designer .Cookie Can provide users with a lot of information to make , For example, a shopping website stores a list of products that users have visited , Or the portal remembers what kind of news users like to browse . With the user's permission , You can still save ...

  5. Incisive jQuery-- To write jQuery plug-in unit ( Reading notes 5 )[ Conclusion ]

    1. Form validation plug-in Validation   2. Form plugin Form   3. Dynamic event binding plug-in livequery You can bind events for later elements   Be similar to jQuery Medium live() Method     4.jQuer ...

  6. JQuery Plug in Jquery.datatables.js Usage and api

    1.DataTables Default configuration $(document).ready(function() { $('#example').dataTable(); } ); Example :http://www.guoxk ...

  7. 15 To help you achieve responsive navigation jQuery plug-in unit

    For most of us , The most difficult aspect of building a responsible layout is the implementation of planning and navigation . Because there is no universal solution that really stands the test , The menu design style you can use will depend on the type of website you are building . No matter what kind of website you're building , stay ...

  8. The first 7 Chapter jQuery How to use and write plug-ins

    The first 7 Chapter jQuery How to use and write plug-ins Plug ins are also called extensions , It's a program written by an application program interface that follows certain specifications . The idea of plug-in is based on object-oriented . Get the latest plug-ins to see jquery Official website :http://plugins. ...

  9. Jquery Plug in implementation Click to get the verification code 60 No reacquiring within seconds

    adopt jquery.cookie.js Plug ins can be implemented quickly “ Click to get the verification code 60 No reacquiring within seconds ( Anti refresh )” The function of Go to the official website first (http://plugins.jquery.com/cookie/ ) download coo ...

Random recommendation

  1. json Object and the json String object format

    var cStr = "{\"c\":\"{\\\"b\\\":\\\"000\\\",\\\"b2\\\&q ...

  2. 【 turn 】sql server Open full text indexing method

    Using system stored procedure to create full-text index : 1) Start the full text processing function of the database (sp_fulltext_database) 2) Set up a full text catalog (sp_fulltext_catalog) 3) In the full text catalog ...

  3. Oracle Synonym creation and assigning user permission to create synonyms

    (1)-- Authorize a user crate synonym Authority , If the user name is scott grant create synonym to scott(2)-- Create synonyms create [or replace] s ...

  4. AngularJS Experience

    AngularJS I learned about it earlier , Know it's a JS Of MVC frame , The same kind of framework is Backbone etc. . This time it's because the project needs , I studied for two days Angular Then start to change the previous project code , Let's talk about this week's study ...

  5. No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android&quot;

    installed NDK I made this mistake when I went to work , The way to go online is to download the old version NDK, Will be one of the toolchain Copy to the new version of NDK in . But it doesn't have to be that much trouble . After a review of the new version NDK The study of , Find out NDK There is a paragraph in the update record of This ...

  6. web socket server code, call shell exec child_process

    var child_process = require('child_process'); var ws = require("nodejs-websocket"); consol ...

  7. JScript Regular expression syntax table

    character describe \ Mark the next character as a special character or text . for example ,"n" And character "n" matching ."\n" Then it matches the newline character . Sequence "\\&qu ...

  8. mysqldump Script crontab Execution failure , But the manual execution succeeded

    Checking the backup found ,cron Regular backup in the network mysql Script backup for failed , But it's manual mysql The backup script works normally Check cron Environment variables of : # cat /etc/crontab ... SHELL=/bin/s ...

  9. linux The configuration vncserver

    vncserver It's a very convenient and extensive Remote Desktop Service , The configuration is relatively simple .  It is recorded below in centos Configuration on the system vncserver The process of . install see centos If it has been installed vncserver rp ...

  10. Jmeter+Ant When generating a result report ,MinTime、MaxTime Show NaN The problem of

    take apache-jmeter-2.13\lib Medium serializer-2.7.2.jar.xalan-2.7.2.jar Copied to the apache-ant-1.9.6\lib Then you can : Generate before copying :