jQuery在重置cookie之前未删除它

4
我正在尝试使用Javascript更新网站的一些cookie。它应该查看现有cookie是否具有某个值。如果是这样,删除cookie并替换它。
但实际上,它只是添加了新的cookie而没有删除原始cookie。
以下是我的代码:
$(document).ready(function(){
if(getCookie('ref') == 'na') {
    $.cookie('ref', null, { path: '/', expires: -5 });
    $.cookie('ref', Base64.encode(document.referrer), { expires: 365 });
}

});

这是我使用的cookie库:https://github.com/carhartl/jquery-cookie 我做错了什么?
1个回答

2
要删除cookie,您必须使用完全相同的路径和域将其设置为要从中删除的路径和域。在两个 $.cookie()调用中都指定 path ,如果在任何先前的代码中指定了 domain ,则必须在jQuery代码中指定该域作为完全匹配项。
$(document).ready(function() {
  if(getCookie('ref') == 'na') {
      $.cookie('ref', null, { path: '/', expires: -5 });
      $.cookie('ref', Base64.encode(document.referrer), {path: '/', expires: 365 });
  }
});

然而,如果你只是想覆盖cookie,实际上并没有真正的必要将其删除:

$(document).ready(function() {
  if(getCookie('ref') == 'na') {
    // Just write the new cookie over the old one...
    $.cookie('ref', Base64.encode(document.referrer), {path: '/', expires: 365 });
  }
 });

我认为路径是问题所在。当我在PHP中设置cookie时,它会在域名前面添加一个句点。我认为这就是JS无法覆盖它的原因。 - liz
@liz 是的,当你尝试覆盖一个cookie时,域名和路径都必须完全匹配。 - Michael Berkowski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接