프로그래밍 언어/jQuery, ajax

jQuery로 쿠키를 set / unset 하는 방법

Rateye 2021. 10. 5. 10:40
728x90
반응형
질문 : jQuery로 쿠키를 어떻게 설정 / 설정 해제합니까?

test 1 설정하는 것과 같이 jQuery를 사용하여 쿠키를 설정 및 설정 해제하는 방법은 무엇입니까?

답변

2019 년 4 월 업데이트

쿠키 읽기 / 조작에는 jQuery가 필요하지 않으므로 아래의 원래 답변을 사용하지 마십시오.

대신 https://github.com/js-cookie/js-cookie로 이동하고 jQuery에 의존하지 않는 라이브러리를 사용하십시오.

기본 예 :

// Set a cookie
Cookies.set('name', 'value');

// Read the cookie
Cookies.get('name') => // => 'value'

자세한 내용은 github의 문서를 참조하십시오.


2019 년 4 월 이전 (구)

플러그인을 참조하십시오.

https://github.com/carhartl/jquery-cookie

그런 다음 다음을 수행 할 수 있습니다.

$.cookie("test", 1);

지우는 것:

$.removeCookie("test");

또한 쿠키에 특정 일 수 (여기서는 10)의 시간 제한을 설정하려면 다음을 수행하십시오.

$.cookie("test", 1, { expires : 10 });

만료 옵션을 생략하면 쿠키가 세션 쿠키가되고 브라우저가 종료 될 때 삭제됩니다.

모든 옵션을 포함하려면 :

$.cookie("test", 1, {
   expires : 10,           // Expires in 10 days

   path    : '/',          // The value of the path attribute of the cookie
                           // (Default: path of page that created the cookie).

   domain  : 'jquery.com', // The value of the domain attribute of the cookie
                           // (Default: domain of page that created the cookie).

   secure  : true          // If set to true the secure attribute of the cookie
                           // will be set and the cookie transmission will
                           // require a secure protocol (defaults to false).
});

쿠키 값을 다시 읽으려면 :

var cookieValue = $.cookie("test");

쿠키가 현재 경로와 다른 경로에 생성 된 경우 경로 매개 변수를 지정할 수 있습니다.

var cookieValue = $.cookie("test", { path: '/foo' });

업데이트 (2015 년 4 월) :

아래 주석에서 언급했듯이 원래 플러그인을 작업 한 팀은 다음과 동일한 기능과 일반 구문을 가진 새 프로젝트 (https://github.com/js-cookie/js-cookie)에서 jQuery 종속성을 제거했습니다. jQuery 버전. 분명히 원래 플러그인은 아무데도 가지 않습니다.

출처 : https://stackoverflow.com/questions/1458724/how-do-i-set-unset-a-cookie-with-jquery
728x90
반응형