test
的cookie并将其值设置为1
?test
的cookie并将其值设置为1
?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("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).
});
读取cookie的值:
var cookieValue = $.cookie("test");
更新(2015年4月):
如下方评论所述,原插件团队已在一个新项目中移除了jQuery依赖项(https://github.com/js-cookie/js-cookie),该项目具有与jQuery版本相同的功能和通用语法。但原插件好像并没有消失。
没有必要特别使用jQuery来操作cookies。
来自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);
}
看看这个:
encodeURIComponent
可能会错误地编码 RFC 6265 中允许在 cookie 值或 cookie 名称中使用的字符:https://github.com/js-cookie/js-cookie/pull/20#issuecomment-94453407。这可能会导致使用第三方解决方案删除 cookie 时出现问题,因为这些解决方案期望 cookie 名称中有一些字符没有被编码。 - Fagner Brack<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)
您可以像这样获取cookies
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();
}
谢谢,维基
é
,北
等。此外,对于一些不允许在cookie名称或cookie值中使用的特殊字符,这也不起作用。我建议参考以下内容:http://tools.ietf.org/html/rfc6265 - Fagner Brack您可以在这里使用可用的插件。
https://plugins.jquery.com/cookie/
然后写入 cookie:
$.cookie("test", 1);
访问该设置的 cookie:
$.cookie("test");
这是我使用的全局模块 -
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);
}
};
请确保不要做这样的事情:
var a = $.cookie("cart").split(",");
如果 cookie 不存在,调试器会返回一些无用的消息,例如“.cookie not a function”。
在检查是否为 null 之后,始终先声明,然后再执行分割操作。像这样:
var a = $.cookie("cart");
if (a != null) {
var aa = a.split(",");
}
缺失还是有几行代码缺失? - Peter Mortensen以下是如何使用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,只需将过期参数设置为一个过去的日期即可:document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
<!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.1.min.js
时,对于每个人jquery-1.9.0.min.js
都将重新加载,否则浏览器不会发出任何请求以检查更新的内容。如果您更新了jquery.cookie.js
内的代码而没有更改它的文件名,则已经缓存了 jquery.cookie.js
资源的浏览器可能不会重新加载它。 - Fagner Brackjquery.cookie.js
版本而不更改其文件名(除非您的服务器使用E-Tags处理缓存),否则此方法将无法正常工作。 - Fagner Brack <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将立即过期 :)
$.removeCookie('nameofcookie', { path: '/' });
- LessQuesarvar cookieValue = $.cookie("test", { path: '/foo' });
不起作用。它设置了一个根路径的 cookie,其中包含一个 JSON 对象{ path: '/foo' }
,并返回 cookie 格式化字符串"test=%5Bobject%20Object%5D"
。请删除此错误代码。不幸的是,jQuery-Cookie 没有一种在不同路径中检索 cookie 的方法,我也没有看到 JS-Cookie 中的任何更新。 - ADTC