JS Cookie在2个地方设置,不会覆盖第一个设置 [英] JS Cookie set in 2 places, doesn't overwrite first set

查看:610
本文介绍了JS Cookie在2个地方设置,不会覆盖第一个设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在2个不同的页面上使用相同的脚本来设置相同的cookie.我的假设是,即使两个页面的路径略有不同,它们也只会覆盖cookie,而不是将条目复制到其中.

I am using the same script on 2 different pages, to set the same cookie. My assumption would be that even though the two pages are (slightly) different paths, they would simply overwrite the cookie instead of duplicating entries into it.

我的第一页路径是:

example.com/classifieds/businesses

我第二页的路径是:

example.com/classifieds/businesses/search

所以,我的问题是,cookie是否与页面相关;我可以强迫他们覆盖现有值,而不是将其特定于页面的值写入Cookie吗?

So, my question is, are cookies page-dependent; can I force them to overwrite existing values instead of writing their own page-specific values to the cookie?

这是重复的我的cookie的样子:

domain=.example.com; path=/; bdView=column; bdView=detail; domain=.example.com;

用于设置域的代码(位于头文件中)

var domain = window.location.host.split(/\.(.+)/)[1];
document.cookie = "domain=." + domain;
document.cookie = "path=/";

用于设置bdView的代码(该代码位于我在两个页面中都包含的单独的js文件中)

function setCookie(view) {
    switch (view) {
        case "column":
            document.cookie = "bdView=column";
            break;
        case "list":
            document.cookie = "bdView=list";
            break;
        case "detail":
            document.cookie = "bdView=detail";
            break;
    }
}

推荐答案

因此,我只是在使用Cookie时出错.我认为该域&路径只是他们自己的东西,但实际上您应该使用要设置的东西来设置它们.

So, I was simply using cookies wrong. I thought that domain & path were just their own things, but you're actually supposed to set them WITH the thing you're trying to set.

因此,它应该看起来像这样:

So, it should look like this instead:

function setCookie(view) {
    var domain = window.location.host.split(/\.(.+)/)[1];
    switch (view) {
        case "column":
            document.cookie = "bdView=column; path=/; domain=" + domain;
            break;
        case "list":
            document.cookie = "bdView=list; path=/; domain=" + domain;
            break;
        case "detail":
            document.cookie = "bdView=detail; path=/; domain=" + domain;
            break;
    }
}

这篇关于JS Cookie在2个地方设置,不会覆盖第一个设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆