4

下面是我试图弄清楚为什么它不能完全工作的例子。

它不断给我空值。

我正在尝试学习如何在单个 cookie 中设置多个值。

每个 cookie 包含一个 name=value 对,因此如果您需要存储多个单独的数据,例如用户名、年龄和会员编号,则需要三个不同的 cookie。

我没有这样做,而是使用分隔符技术来拆分它,这样我就可以使用更少的 cookie。

如果可以的话,请告诉我任何正确实施的例子。我看过一些其他编程语言的材料,但我想知道它是如何在 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>
4

3 回答 3

2


不要使用“|” 作为分隔符,它在不同浏览器中的实现方式不同(使用“-”、“+”、“.”等作为分隔符)。当我检查 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>

当我测试这个时,它工作正常:它保存“Joe” name,“31”age和“Athlete”job
我添加了一些调试警报,这样你也可以测试它
,我希望我能帮忙:)

于 2013-05-27T20:28:32.020 回答
1

好吧,至于 Sven L 提到的分隔符。你有Joe%7C31%7CAthlete因为

  • %7C是 char 竖线“ | ”的 url 编码值

至于提到的其他分隔符,请参阅cookies 中允许的字符

至于我在Firefox中,'-'和'。未编码存储在单字节中,但“+”已转换为其编码值 %2B

选择不会被编码的分隔符是有意义的。这样分隔符将只占用 1 个字节。因此,考虑到 4kB 的大小限制,可以将更多有用的东西放入 cookie 值中。

于 2015-09-11T08:24:02.930 回答
0

For me your code works perfectly on 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.

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 -m SimpleHTTPServer 8000

Then, just go to http://127.0.0.1:8000 with your browser and the Web site should work.

Of course you can also use any other http server, like apache or whatever you'd like.

于 2013-05-27T20:40:05.427 回答