javascript 如何使用分隔符在单个 cookie 中设置多个值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16779635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set multiple values in a single cookie using a delimiter?
提问by weichan8t1
Below is the example that I am trying to figure out why it doesn't work exactly.
下面是我试图弄清楚为什么它不能完全工作的示例。
It keeps giving me null values.
它不断给我空值。
I am trying to learn how to set multiple values in a single cookie.
我正在尝试学习如何在单个 cookie 中设置多个值。
Each cookie contains one name=value pair, so if you need to store several separate pieces of data such as user's name, age, and membership number, you need three different cookies.
每个 cookie 包含一个名称=值对,因此如果您需要存储多个单独的数据,例如用户名、年龄和会员编号,则需要三个不同的 cookie。
Instead of doing that, I'm using a delimiter technique to split it so I can use fewer cookies.
我没有这样做,而是使用分隔符技术来拆分它,这样我就可以使用更少的 cookie。
Please show me any examples of this correctly implemented if you can. I've seen some material for other programming languages but I would like to know how it is done in JavaScript specifically.
如果可以,请向我展示正确实施的任何示例。我看过其他编程语言的一些材料,但我想知道它是如何在 JavaScript 中完成的。
<!DOCTYPE html>
<html>
<head>
<title> Using a delimiter to save on cookies used</title>
<script>
function createCookie(name, value, days, path, domain, secure) {
if (days) {
var date=new Date();
date.setTime(date.getTime()+ (days*24*60*60*1000));
var expires=date.toGMTString();
}
else var expires = "";
cookieString= name + "=" + escape (value);
if (expires)
cookieString += "; expires=" + expires;
if (path)
cookieString += "; path=" + escape (path);
if (domain)
cookieString += "; domain=" + escape (domain);
if (secure)
cookieString += "; secure";
document.cookie=cookieString;
}
function getCookie(name) {
var nameEquals = name + "=";
var crumbs=document.cookie.split('|');
for (var i = 0; i<crumbs.length; i++) {
var crumb = crumbs [i];
if (crumb.indexOf(nameEquals) == 0) {
return unescape (crumb.substring(nameEquals.length, crumb.length));
}
}
return null;
}
function deleteCookie(name){
createCookie(name, "", -1);
}
var userdata="Joe|31|Athlete";
createCookie("user", userdata);
var myUser=getCookie("user");
var myUserArray=myUser.split('|');
var name=myUserArray[0];
var age=myUserArray[1];
var profession=myUserArray[2];
</script>
</head>
<body>
</body>
</html>
回答by svenlr
don't use '|' as a delimiter, its implemented differently in different browsers (use such things as '-', '+', '.' etc for your delimiter). when i check firefox > site information, it tells me that there is a cookie, but that the content is Joe%7C31%7CAthlete
. in my version, i put the delimiter in a variable that we define before everything (i took '---', but you can change it if you want):
不要使用“|” 作为分隔符,它在不同浏览器中的实现方式不同(使用诸如“-”、“+”、“.”等作为分隔符)。当我检查 firefox > 站点信息时,它告诉我有一个 cookie,但内容是Joe%7C31%7CAthlete
. 在我的版本中,我将分隔符放在我们在所有内容之前定义的变量中(我使用了“---”,但您可以根据需要更改它):
<!DOCTYPE html>
<html>
<head>
<title> Using a delimiter to save on cookies used</title>
<script>
var delimiter = "---";
function createCookie(name, value, days, path, domain, secure) {
if (days) {
var date=new Date();
date.setTime(date.getTime()+ (days*24*60*60*1000));
var expires=date.toGMTString();
}
else var expires = "";
cookieString= name + "=" + escape (value);
if (expires)
cookieString += "; expires=" + expires;
if (path)
cookieString += "; path=" + escape (path);
if (domain)
cookieString += "; domain=" + escape (domain);
if (secure)
cookieString += "; secure";
document.cookie=cookieString;
}
function getCookie(name) {
var nameEquals = name + "=";
var whole_cookie=document.cookie.split(nameEquals)[1].split(";")[0]; // get only the value of the cookie we need
// (split by the name=, take everything after the name= and then split it by ";" and take everything before the ";")
var crumbs=whole_cookie.split(delimiter); // split now our cookie in its information parts
/*for (var i = 0; i<crumbs.length; i++) {
var crumb = crumbs [i];
if (crumb.indexOf(nameEquals) == 0) {
return unescape (crumb.substring(nameEquals.length, crumb.length));
}
}*/ // sorry... i dont understand what this does ;) but it works without it
return crumbs; // return the information parts as an array
}
function deleteCookie(name){
createCookie(name, "", -1);
}
// ---------------------
// DEBUGGING PART STARTS
// ---------------------
var userdata="Joe"+delimiter+"31"+delimiter+"Athlete";
createCookie("user", userdata);
var myUserArray=getCookie("user");
var name=myUserArray[0];
var age=myUserArray[1];
var profession=myUserArray[2];
alert(myUserArray[0]);
alert(myUserArray[1]);
alert(myUserArray[2]);
// ---------------------
// DEBUGGING PART ENDS
// ---------------------
</script>
</head>
<body>
</body>
</html>
when i test this, it works correctly: it saves "Joe" in name
, "31" in age
and "Athlete" in job
i added some alert for debugging so that you can test it too
bye, i hope i could help :)
当我测试这个时,它工作正常:它保存了“Joe” name
,“31”age
和“Athlete”,job
我添加了一些调试警报,这样你也可以测试它,
再见,我希望我能帮助:)
回答by Alf Tau
Well, as to delimiters mentioned by Sven L. You've got Joe%7C31%7CAthletebecause
好吧,至于 Sven L 提到的分隔符。你有Joe%7C31%7CAthlete因为
- %7Cis an url encoded value for char vertical bar "|"
- %7C是字符竖线“ |”的 url 编码值
As to other separators mentioned, please see Allowed characters in cookies.
至于提到的其他分隔符,请参阅cookies 中允许的字符。
As for me in firefox, '-' and '.' were stored unencoded in single byte but '+' was converted to its encoded value %2B
至于我在 Firefox 中,'-' 和 '.' 未编码存储在单字节中,但“+”已转换为其编码值 %2B
It makes sense to choose separators that won't be encoded. This way the separator will only take 1 byte. So, one can put more useful stuff into cookie value taking into account its size limit of 4kB.
选择不会被编码的分隔符是有意义的。这样分隔符将只占用 1 个字节。因此,考虑到 4kB 的大小限制,可以将更多有用的东西放入 cookie 值中。
回答by zeroos
For me your code works perfectly on Chrome.
对我来说,您的代码在 Chrome 上运行良好。
However, I have had to run it on a web server - if I just open a html file it does not save any cookies.
但是,我不得不在网络服务器上运行它 - 如果我只是打开一个 html 文件,它不会保存任何 cookie。
If you have python installed on your machine you can run a minimalistic python server with this command from the directory with html files you want to serve:
如果你的机器上安装了 python,你可以使用这个命令从你想要提供的 html 文件的目录中运行一个简约的 python 服务器:
$ python -m SimpleHTTPServer 8000
Then, just go to http://127.0.0.1:8000
with your browser and the Web site should work.
然后,只需http://127.0.0.1:8000
使用您的浏览器转至该网站即可。
Of course you can also use any other http server, like apache or whatever you'd like.
当然,您也可以使用任何其他 http 服务器,例如 apache 或您喜欢的任何服务器。