jQuery Cookie路径

wat*_*ats 32 javascript cookies jquery

我使用jQuery cookie插件来存储cookie,使用以下代码我可以将Cookie保存7天,但它只保存它创建的页面.我希望cookie可用于整个网站.

$.cookie('basket',basket,{ expires: 7 });
Run Code Online (Sandbox Code Playgroud)

我试图设置一条路径,但这似乎不起作用

$.cookie('basket',basket,{ expires: 7, path:'/' });
Run Code Online (Sandbox Code Playgroud)

完整代码:这个工作正常,但它只保存当前页面的cookie

function add_to_basket(id,title){
if($.cookie('basket')){
    basket=$.cookie('basket');

    var basket_array = basket.split(',');

    var index = jQuery.inArray(id,basket_array);
    if(index > -1){
        return false;
    }else{
        basket+=','+id;
        $.cookie('basket',basket,{ expires: 7 });
    }
}else{

    basket=id;
    console.log(basket);
    $.cookie('basket',basket,{ expires: 7 });

}
Run Code Online (Sandbox Code Playgroud)

Tim*_*ord 51

我刚遇到同样的问题.我通过在编写cookie时始终指定路径来修复它.

$.cookie('basket', value, { path: '/' })
Run Code Online (Sandbox Code Playgroud)

这是jquery cookie插件的问题.它将默认为当前页面的路径.

  • 当我尝试这种方法时,它实际上将cookie(在你的情况下为'basket')设置为具有path属性的对象,而不是检索cookie. (9认同)
  • 这是为了将cookie设置为给定路径,而不是检索. (2认同)

bit*_*ove 14

在插件文件中更改:

config.defaults = {};

config.defaults = {path:'/'};

来自https://github.com/carhartl/jquery-cookie/issues/2#issuecomment-790288