提问人:omg 提问时间:9/22/2009 最后编辑:Kamil Kiełczewskiomg 更新时间:9/30/2022 访问量:1483626
如何使用jQuery设置/取消设置cookie?
How do I set/unset a cookie with jQuery?
答:
更新于 2019 年 4 月
cookie 读取/操作不需要 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");
此外,要在 cookie 上设置一定天数(此处为 10 天)的超时:
$.cookie("test", 1, { expires : 10 });
如果省略 expires 选项,则 cookie 将成为会话 cookie,并在浏览器退出时被删除。
要涵盖所有选项,请执行以下操作:
$.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).
});
要读回 cookie 的值,请执行以下操作:
var cookieValue = $.cookie("test");
更新(2015 年 4 月):
如下面的评论所述,开发原始插件的团队已经删除了新项目 (https://github.com/js-cookie/js-cookie) 中的 jQuery 依赖项,该项目具有与 jQuery 版本相同的功能和通用语法。显然,原始插件不会去任何地方。
评论
$.removeCookie('nameofcookie', { path: '/' });
您可以使用此处提供的插件。
https://plugins.jquery.com/cookie/
然后写一个cookie做$.cookie("test", 1);
要访问设置的 cookie,请执行$.cookie("test");
评论
没有必要特别使用jQuery来操作cookie。
从 QuirksMode(包括转义字符)
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = encodeURIComponent(name) + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ')
c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0)
return decodeURIComponent(c.substring(nameEQ.length, c.length));
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
看一看
评论
在浏览器中设置cookie的简单示例:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jquery.cookie Test Suite</title>
<script src="jquery-1.9.0.min.js"></script>
<script src="jquery.cookie.js"></script>
<script src="JSON-js-master/json.js"></script>
<script src="JSON-js-master/json_parse.js"></script>
<script>
$(function() {
if ($.cookie('cookieStore')) {
var data=JSON.parse($.cookie("cookieStore"));
$('#name').text(data[0]);
$('#address').text(data[1]);
}
$('#submit').on('click', function(){
var storeData = new Array();
storeData[0] = $('#inputName').val();
storeData[1] = $('#inputAddress').val();
$.cookie("cookieStore", JSON.stringify(storeData));
var data=JSON.parse($.cookie("cookieStore"));
$('#name').text(data[0]);
$('#address').text(data[1]);
});
});
</script>
</head>
<body>
<label for="inputName">Name</label>
<br />
<input type="text" id="inputName">
<br />
<br />
<label for="inputAddress">Address</label>
<br />
<input type="text" id="inputAddress">
<br />
<br />
<input type="submit" id="submit" value="Submit" />
<hr>
<p id="name"></p>
<br />
<p id="address"></p>
<br />
<hr>
</body>
</html>
只需复制/粘贴并使用此代码来设置您的cookie。
评论
jquery-1.9.0.min.js
jquery-1.9.1.min.js
jquery.cookie.js
jquery.cookie.js
jquery.cookie.js
<script type="text/javascript">
function setCookie(key, value, expiry) {
var expires = new Date();
expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}
function getCookie(key) {
var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
return keyValue ? keyValue[2] : null;
}
function eraseCookie(key) {
var keyValue = getCookie(key);
setCookie(key, keyValue, '-1');
}
</script>
您可以将 cookie 设置为
setCookie('test','1','1'); //(key,value,expiry in days)
您可以像这样获得 cookie
getCookie('test');
最后,您可以像这样擦除 cookie
eraseCookie('test');
希望它能对某人有所帮助:)
编辑:
如果要将 cookie 设置为所有路径/页面/目录,请将 path 属性设置为 cookie
function setCookie(key, value, expiry) {
var expires = new Date();
expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
document.cookie = key + '=' + value + ';path=/' + ';expires=' + expires.toUTCString();
}
谢谢 维 琪
评论
é
北
确保不要做这样的事情:
var a = $.cookie("cart").split(",");
然后,如果 cookie 不存在,调试器将返回一些无用的消息,例如“.cookie 不是函数”。
始终先声明,然后在检查 null 后进行拆分。喜欢这个:
var a = $.cookie("cart");
if (a != null) {
var aa = a.split(",");
评论
}
我认为 Fresher 给了我们很好的方法,但有一个错误:
<script type="text/javascript">
function setCookie(key, value) {
var expires = new Date();
expires.setTime(expires.getTime() + (value * 24 * 60 * 60 * 1000));
document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}
function getCookie(key) {
var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
return keyValue ? keyValue[2] : null;
}
</script>
你应该在 getTime() 附近添加 “value”;否则,cookie将立即过期:)
评论
您可以在此处使用Mozilla网站上的库
您将能够设置和获取这样的 cookie
docCookies.setItem(name, value);
docCookies.getItem(name);
这是我使用的全局模块 -
var Cookie = {
Create: function (name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=/";
},
Read: function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(";");
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == " ") c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
},
Erase: function (name) {
Cookie.create(name, "", -1);
}
};
以下是使用 JavaScript 设置 cookie 的方法:
以下代码取自 https://www.w3schools.com/js/js_cookies.asp
function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+ d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; }
现在,您可以使用以下功能获取cookie:
function getCookie(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for(var i = 0; i <ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; }
最后,这是您检查cookie的方式:
function checkCookie() { var username = getCookie("username"); if (username != "") { alert("Welcome again " + username); } else { username = prompt("Please enter your name:", ""); if (username != "" && username != null) { setCookie("username", username, 365); } } }
如果要删除 cookie,只需将 expires 参数设置为传递的日期:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
我认为 Vignesh Pichamani 的答案是最简单、最干净的。只是增加了他设置到期前天数的能力:
编辑:如果未设置日期数,还添加了“永不过期”选项
function setCookie(key, value, days) {
var expires = new Date();
if (days) {
expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
} else {
document.cookie = key + '=' + value + ';expires=Fri, 30 Dec 9999 23:59:59 GMT;';
}
}
function getCookie(key) {
var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
return keyValue ? keyValue[2] : null;
}
设置 cookie:
setCookie('myData', 1, 30); // myData=1 for 30 days.
setCookie('myData', 1); // myData=1 'forever' (until the year 9999)
如何使用它?
//To set a cookie
$.cookie('the_cookie', 'the_value');
//Create expiring cookie, 7 days from then:
$.cookie('the_cookie', 'the_value', { expires: 7 });
//Create expiring cookie, valid across entire page:
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
//Read cookie
$.cookie('the_cookie'); // => 'the_value'
$.cookie('not_existing'); // => null
//Delete cookie by passing null as value:
$.cookie('the_cookie', null);
// Creating cookie with all availabl options
$.cookie('myCookie2', 'myValue2', { expires: 7, path: '/', domain: 'example.com',
secure: true, raw: true });
可用选项:
expires:定义 Cookie 的生存期。值可以是 Number(将解释为创建后的天数)或 Date 对象。如果省略,则 cookie 是会话 cookie。
path:定义 cookie 有效的路径。默认情况下,Cookie 的路径是创建 Cookie 的页面的路径(标准浏览器行为)。例如,如果要使其在整个页面上可用,请使用路径:“/”。
domain:创建 Cookie 的页面的域。
secure:默认值:false。如果为 true,则 cookie 传输需要安全协议 (https)。
raw:默认情况下,在创建/读取时,使用 encodeURIComponent/decodeURIComponent 对 cookie 进行编码/解码。通过设置 raw: true 关闭。
我知道有很多很好的答案。通常,我只需要读取 cookie,我不想通过加载额外的库或定义函数来产生开销。
以下是如何在一行 javascript 中读取 cookie。我在 Guilherme Rodrigues 的博客文章中找到了答案:
('; '+document.cookie).split('; '+key+'=').pop().split(';').shift()
这读作名为 , nice, clean and simple 的 cookie。key
尝试(此处为文档,SO 代码片段不起作用,因此运行此代码片段)
document.cookie = "test=1" // set
document.cookie = "test=1;max-age=0" // unset
以下代码将删除当前域和所有尾随子域(、、等)中的所有 cookie。www.some.sub.domain.com
.some.sub.domain.com
.sub.domain.com
单行原版JS版本(无需jQuery):
document.cookie.replace(/(?<=^|;).+?(?=\=|;|$)/g, name => location.hostname.split('.').reverse().reduce(domain => (domain=domain.replace(/^\.?[^.]+/, ''),document.cookie=`${name}=;max-age=0;path=/;domain=${domain}`,domain), location.hostname));
这是此单行的可读版本:
document.cookie.replace(
/(?<=^|;).+?(?=\=|;|$)/g,
name => location.hostname
.split(/\.(?=[^\.]+\.)/)
.reduceRight((acc, val, i, arr) => i ? arr[i]='.'+val+acc : (arr[i]='', arr), '')
.map(domain => document.cookie=`${name}=;max-age=0;path=/;domain=${domain}`)
);
我知道,已经有很多答案了,但这里有一个已经设置
、获取
和删除
了所有精美的香草,并很好地放入全局参考中:
window.cookieMonster = window.cookieMonster ||
{
// https://stackoverflow.com/a/25490531/1028230
get: function (cookieName) {
var b = document.cookie.match('(^|;)\\s*' + cookieName + '\\s*=\\s*([^;]+)');
return b ? b.pop() : '';
},
delete: function (name) {
document.cookie = '{0}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;'
.replace('{0}', name);
},
set: function (name, value) {
document.cookie =
'{0}={1};expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/;SameSite=Lax'
.replace('{0}', name)
.replace('{1}', value);
}
};
请注意,cookie 获取正则表达式是从另一个城堡中一个问题的答案中获取的。
让我们测试一下:
cookieMonster.set('chocolate', 'yes please');
cookieMonster.set('sugar', 'that too');
console.log(cookieMonster.get('chocolate'));
console.log(document.cookie);
cookieMonster.delete('chocolate');
console.log(cookieMonster.get('chocolate'));
console.log(document.cookie);
如果您在尝试之前没有任何饼干,应该给您...
yes please
chocolate=yes please; sugar=that too
sugar=that too
请注意,饼干的持续时间并不长,但从我们的角度来看,本质上是这样。您可以通过查看此处的字符串或其他答案来轻松更改日期。
与以前的答案相比,减少了操作次数,我使用以下方法。
function setCookie(name, value, expiry) {
let d = new Date();
d.setTime(d.getTime() + (expiry*86400000));
document.cookie = name + "=" + value + ";" + "expires=" + d.toUTCString() + ";path=/";
}
function getCookie(name) {
let cookie = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return cookie ? cookie[2] : null;
}
function eatCookie(name) {
setCookie(name, "", -1);
}
背景
Cookie 最初是由 Netscape 发明的,用于为 Web 服务器和浏览器提供“内存”。HTTP协议是无状态的,该协议安排将网页传输到您的浏览器,并将页面请求发送到服务器,这意味着一旦服务器将页面发送到请求它的浏览器,它就不会记住任何事情。因此,如果您第二次、第三次、第一百次或第一百万次访问同一网页,服务器会再次将其视为您第一次访问该网页。
这在很多方面都可能很烦人。当您要访问受保护的页面时,服务器无法记住您是否标识了自己,它无法记住您的用户首选项,它无法记住任何内容。一旦个性化被发明出来,这就成为一个主要问题。
饼干就是为了解决这个问题而发明的。还有其他方法可以解决这个问题,但 cookie 易于维护且用途广泛。
Cookie 的工作原理
Cookie 只不过是存储在浏览器中的一个小文本文件。它包含一些数据:
- 包含实际数据的名称/值对
- 到期日后不再有效
- 应发送到的服务器的域和路径
例
要使用 Javascript 设置或取消设置 Cookie,您可以执行以下操作:
// Cookies
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function setCookie(name, days) {
createCookie(name, name, days);
}
function unsetCookie(name) {
createCookie(name, "", -1);
}
您可以像下面这样访问,
setCookie("demo", 1); // to set new cookie
readCookie("demo"); // to retrive data from cookie
unsetCookie("demo"); // will unset that cookie
评论