简体   繁体   English

Cookie的多个值

[英]Multiple values for cookies

I'm new to this and I'm trying to figure it out what is the best way of setting multiple values for a cookie/cookies. 我是新手,因此我想弄清楚为cookie设置多个值的最佳方法是什么。 I need to store around 10 parameters(different) values(for different scenarios) in a cookies, but I have a serious doubt about this, because as far as I know cookie accept only one parameter value and therefor I will need around 10 cookies! 我需要在cookie中存储大约10个参数(不同的值)(针对不同的场景),但是对此我有一个严重的疑问,因为据我所知,cookie只接受一个参数值,因此,我将需要大约10个cookie! I think it's too much, I never seen anything like this for other websites. 我认为这太多了,我从未在其他网站上看到过类似的内容。

I'm setting the cookie like that when it's needed: 我在需要时就这样设置cookie:

document.cookie = 'yesno=yes; path=/';

Would be nice to hear how is it needed to be done 很高兴听到需要怎么做

    var  common={
setCookie:function (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;
},
getCookie:function getCookie(cname) {
    var name = cname + "=";
    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);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}};common.setCookie('tz',tz,30);

If it doesn't need to be a cookie, and you simply want to save value on the visitors browser between requests, then you can use localStorage . 如果不需要cookie,而您只是想在localStorage请求之间在访问者浏览器上保存价值,则可以使用localStorage It's far simpler than trying set and parse the cookie string format. 这比尝试设置和解析cookie字符串格式要简单得多。

Docs: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage 文件: https//developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

localStorage.setItem('yesno', 'yes');
localStorage.getItem('yesno'); //=> 'yes'

The main difference between this and cookies is that cookies get sent to the server along with every request, where local storage does not. 这和cookie之间的主要区别是cookie随每个请求一起发送到服务器,而本地存储则不发送。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM