我正在尝试用JS弄清楚cookie并且我完全迷失了,用PHP这么容易。我有这行代码可以有人向我解释这意味着什么?
function setCookie(name, value, expires) {
document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : ";
expires=" + expires.toGMTString());
}
答案 0 :(得分:3)
http://www.quirksmode.org/js/cookies.html有更多信息......
JS中的+
等同于PHP中的.
(连接)...所以你要从输入构建一个字符串,并相应地格式化各个部分(比如转换{{1} }})
然后,document.cookie = {that string}设置它
答案 1 :(得分:1)
document.cookie
接受key=value
形式的字符串来设置Cookie。
可以从Mozilla
cookie属性值可以选择跟随键值对,指定要设置/更新的cookie,前面有分号分隔符:
根据此规范,此字符串应为name=value ;expires=date ;domain=domain ;path=path
在您的情况下,+
运算符的行为与PHP中的.
运算符相同。它执行字符串协商。
var b = 'I' + ' am' + ' a' + ' JavaScript' +' hacker.'
>>'I am a JavaScript hacker.'
为了减轻您的痛苦,我建议使用jquery.cookie
plugin。
设置Cookie
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
获取cookie
$.cookie('the_cookie');
删除Cookie
$.cookie('the_cookie', null);
答案 2 :(得分:1)
Cookies有几个部分,其中许多是可选的
Tokens: name=value ;expires=date ;domain=domain ;path=path
escape(value)
转义非字母数字字符,例如空格和特殊字符
用十六进制equilivments替换它们
比如%hh,一个空格将是%20
path = /“域中路径的子集”/“第一条路径下的所有内容
path = / users /例如要访问它,您需要在/ users /
中 + ((expires == null) ? "" : "
; expires=" + expires.toGMTString())
;
?: oporator
(表达)? if-true-statement:if-false-statement;
?:可以使用oporator whare if cannot
dose (expires equal null) ?
//没有expires字段设置的cookie称为会话cookie。
( if true set empty string "" )
else
//将令牌过期宽度设为日期
( if not null set the expires token)