Home  >  Article  >  Web Front-end  >  Detailed analysis of jquery.cookie usage_jquery

Detailed analysis of jquery.cookie usage_jquery

WBOY
WBOYOriginal
2016-05-16 17:08:411311browse

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:

d9adef48bd8eb639ce295ee4c679039b2cacc6d41bbb37262a98f745aa00fbf0
6ea3bd74ac09c0e98bf4257db9cb49762cacc6d41bbb37262a98f745aa00fbf0

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

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>

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

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

jquery.cookie.js 구성

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

967ba072082ba7f55ea5396b9cdf91542cacc6d41bbb37262a98f745aa00fbf0 24072ae8460dd165378b4c66bd005edd2cacc6d41bbb37262a98f745aa00fbf0


사용방법

새 세션 쿠키 추가:

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