search
HomeWeb Front-endJS TutorialDetailed analysis of jquery.cookie usage_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  
    }  
  });

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 라이브러리 파일을 포함하세요



사용방법

새 세션 쿠키 추가:

$.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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use