如何使用jQuery设置和取消设置cookie,例如创建一个名为test的cookie并将值设置为1?
当前回答
<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>
你可以把饼干设置成
setCookie('test','1','1'); //(key,value,expiry in days)
你可以拿饼干
getCookie('test');
最后你可以像这样擦掉这些饼干
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();
}
谢谢, 维姬
其他回答
我知道有很多很好的答案。通常,我只需要读取cookie,不希望通过加载额外的库或定义函数来增加开销。
下面是如何在一行javascript中读取cookie。我在Guilherme Rodrigues的博客文章中找到了答案:
('; '+document.cookie).split('; '+key+'=').pop().split(';').shift()
这读取cookie命名为key,漂亮,干净和简单。
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版本相同的功能和通用语法。显然,原来的插件并没有去任何地方。
在浏览器中设置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。
<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>
你可以把饼干设置成
setCookie('test','1','1'); //(key,value,expiry in days)
你可以拿饼干
getCookie('test');
最后你可以像这样擦掉这些饼干
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();
}
谢谢, 维姬
背景
cookie最初是由网景公司发明的,目的是为网络服务器和浏览器提供“内存”。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
推荐文章
- 使用jQuery以像素为整数填充或边距值
- 检查是否选择了jQuery选项,如果没有选择默认值
- Next.js React应用中没有定义Window
- 如何重置笑话模拟函数调用计数之前,每次测试
- 如何强制一个功能React组件渲染?
- 在javascript中从平面数组构建树数组
- 将Dropzone.js与其他字段集成到现有的HTML表单中
- 如何在AngularJS中观察路由变化?
- JavaScript DOM删除元素
- 将dd-mm-yyyy字符串转换为日期
- Javascript复选框onChange
- Javascript函数前导bang !语法
- 如何在页面上遍历所有DOM元素?
- 使用jQuery滚动到一个div
- 在JS/jQuery中触发按键/按键/按键事件?