Home Web Front-end JS Tutorial Detailed analysis of jquery.cookie usage_jquery

Detailed analysis of jquery.cookie usage_jquery

May 16, 2016 pm 05:08 PM
cookie jquery

Cookie is generated by the server and sent to the User-Agent (usually a browser). The browser will save the key/value of the cookie to a text file in a certain directory and send it the next time the same website is requested. This cookie is given to the server (provided the browser is set to enable cookies).

For example, a shopping website stores product lists that users have browsed, or a portal website remembers what type of news a user likes to browse. With the user's permission, could it also be possible to store the user's login information so that the user does not have to type it in each time they visit the website?

How to handle cookies in js/jquery? Today I will share a cookie operation class - jQuery.Cookie.js, which is a lightweight cookie management plug-in.

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

Special reminder, a special error was discovered today. Google browser prompted: has no method $.cookie. Firefox browser prompts: $.cookie is not a function; After debugging for a long time, I finally found the reason. If the same page introduces the Jquery plug-in twice or multiple times, this error will be reported.

How to use:

1. Introduce jQuery and jQuery.Cookie.js plug-ins.

Copy code The code is as follows:



2. Write cookie to file

 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  
    }  
  });
Copy after login

Function.

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

 (1) Read cookie value

$.cookie(cookieName) cookieName: The name of the cookie to be read.

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

 (2) Write the set cookie value:

$.cookie(cookieName,cookieValue); cookieName: the name of the cookie to be set, cookieValue represents the corresponding value.

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

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

 (3) [option] Parameter description:

Expires: Limited date, which can be an integer or a date (unit: days). You should also pay attention here. If you don’t set this thing, the cookie will become invalid after the browser is closed

Path: The path where the cookie value is saved. By default, it is consistent with the path of the created page.

domin: cookie domain name attribute, the default is the same as the domain name of the created page. You should pay great attention to this place. The concept of cross-domain. If you want the primary domain name and the secondary domain name to be valid, you must set ".xxx.com"

secure: A Boolean value indicating whether a security protocol is required when transmitting cookie values.

Example:

Copy code The code is as follows:

$.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"> 
<head> 
  <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> 
</head> 
<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> 
</html>
Copy after login

A cookie is essentially a txt text, so it can only be stored in a string. The object usually needs to be serialized before it can be stored in the cookie, and when retrieved, it must be deserialized to get the object again.

$(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);        //输反序列化出来的对象的姓名值 
     } 
   })
Copy after login

쿠키를 읽고, 쓰고, 삭제할 수 있는 경량 쿠키 플러그인입니다.

jquery.cookie.js 구성

jQuery 라이브러리 파일을 먼저 포함시킨 후 jquery.cookie.js 라이브러리 파일을 포함하세요



사용방법

새 세션 쿠키 추가:

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

참고: 쿠키 유효 기간을 지정하지 않으면 생성된 쿠키는 기본적으로 사용자가 브라우저를 닫을 때까지 유효하므로 이를 "세션 쿠키"라고 합니다.


쿠키를 생성하고 유효 기간을 7일로 설정하세요:

$.cookie('the_cookie', 'the_value', { 만료일: 7 });

참고: 쿠키 유효 기간이 지정되면 생성된 쿠키를 "영구 쿠키"라고 합니다.

쿠키를 생성하고 쿠키에 대한 유효한 경로를 설정합니다:

$.cookie('the_cookie', 'the_value', { 만료: 7, 경로: '/' });

참고: 기본적으로 쿠키를 설정한 웹페이지에서만 쿠키를 읽을 수 있습니다. 다른 페이지에서 설정한 쿠키를 해당 페이지에서 읽을 수 있도록 하려면 쿠키 경로를 설정해야 합니다.

쿠키 경로는 쿠키를 읽을 수 있는 최상위 디렉터리를 설정하는 데 사용됩니다. 이 경로를 웹사이트의 루트 디렉터리로 설정하면 모든 웹페이지가 서로의 쿠키를 읽을 수 있습니다. (일반적으로 충돌을 방지하려면 이 경로를 설정하지 마세요.)


쿠키 읽기:

$.cookie('the_cookie');

// 쿠키가 존재함 => 'the_value' $.cookie('not_existing') // 쿠키가 존재하지 않음 =>

쿠키를 삭제하려면 쿠키 값으로 null을 전달하세요.


$.cookie('the_cookie', null);

관련 매개변수 설명
만료: 365

쿠키의 유효 시간을 정의합니다. 값은 1(쿠키가 생성된 날짜로부터 일 단위) 또는 날짜일 수 있습니다.

생략할 경우 생성된 쿠키는 세션 쿠키이며 사용자가 브라우저를 종료할 때 삭제됩니다.


경로: '/'

기본값: 쿠키를 설정한 웹페이지만 쿠키를 읽을 수 있습니다.

쿠키의 유효한 경로를 정의합니다. 기본적으로 이 매개변수의 값은 쿠키가 생성된 웹 페이지의 경로입니다(표준 브라우저 동작).

웹사이트 전체에서 이 쿠키에 액세스하려면 경로: '/'와 같이 유효 경로를 설정해야 합니다.

유효한 경로가 정의된 쿠키를 삭제하려면 함수 호출 시 $.cookie('the_cookie', null, { path: '/' }); 경로를 포함해야 합니다.

도메인: 'example.com'


기본값: 쿠키를 생성한 웹페이지가 소유한 도메인 이름입니다.


보안: 사실

기본값: 거짓. true인 경우 쿠키 전송에는 보안 프로토콜(HTTPS)을 사용해야 합니다.


원시: 사실

기본값: 거짓. 기본적으로 쿠키를 읽고 쓸 때 인코딩 및 디코딩이 자동으로 수행됩니다(인코딩하려면 encodeURIComponent를 사용하고 디코딩하려면 decodeURIComponent 사용).

이 기능을 끄려면 raw: true로 설정하면 됩니다.

$.cookie('the_cookie'); // 쿠키 가져오기 $.cookie('the_cookie', 'the_value') // 쿠키 설정 $.cookie('the_cookie', 'the_value', { 만료: 7 }); / 만료 날짜가 7일 후인 쿠키를 설정합니다. $.cookie('the_cookie', '', {expires: -1 }) // 쿠키 삭제

$.cookie('the_cookie', null); // 쿠키 삭제

$.cookie('the_cookie','the_value', {expires: 7, path: '/', domain:'80tvb.com', secure: true});//호출 방법 완료


//또는 다음: $.cookie('the_cookie','the_value');

//쿠키 삭제: $.cookie('the_cookie',null);

쿠키를 운용하는 jQuery 플러그인으로, 대략적인 사용방법은 다음과 같습니다 $.cookie('the_cookie') //쿠키 값 읽기

$.cookie('the_cookie', 'the_value'); //쿠키 값 설정

$.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});//유효 기간, 경로 도메인 이름을 포함하는 새 쿠키 생성 등
$.cookie('the_cookie', 'the_value'); //새 쿠키 생성
$.cookie('the_cookie', null); //쿠키 삭제

jquery는 쿠키 만료 시간을 설정하고 쿠키 사용 가능 여부를 확인합니다

x분 후에 쿠키가 만료되도록 허용

var 날짜 = 새 날짜();
date.settime(date.gettime() (x * 60 * 1000));
$.cookie('example', 'foo', { 만료: 날짜 });

$.cookie('example', 'foo', { 만료: 7});

쿠키 사용 가능 여부 확인
$(document).ready(function() {var dt = new date();dt.setseconds(dt.getseconds() 60);document.cookie = “cookietest=1; 만료=” dt.togmtstring( );var cookieenabled = document.cookie.indexof(“cookietest=") != -1;if(!cookiesenabled){//쿠키를 사용할 수 없습니다……..}});

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

Introduction to how to add new rows to a table using jQuery Introduction to how to add new rows to a table using jQuery Feb 29, 2024 am 08:12 AM

jQuery is a popular JavaScript library widely used in web development. During web development, it is often necessary to dynamically add new rows to tables through JavaScript. This article will introduce how to use jQuery to add new rows to a table, and provide specific code examples. First, we need to introduce the jQuery library into the HTML page. The jQuery library can be introduced in the tag through the following code:

See all articles