$.cookie()存在,但未被确认

$.cookie() exists but isn't acknowledged.

本文关键字:确认 存在 cookie      更新时间:2023-09-26

我正在使用jQuery cookie来确定用户是否希望查看移动站点。

当用户点击链接"查看全站"时,他们被带到主页,url参数为:fullscreen=yes

$.extend({
   getUrlVars: function(){
      var vars = [], hash;
      var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
     for(var i = 0; i < hashes.length; i++)
      {
         hash = hashes[i].split('=');
         vars.push(hash[0]);
         vars[hash[0]] = hash[1];
     }
     return vars;
   },
   getUrlVar: function(name){
   }
});

如果设置了该参数,则创建cookie:

if ($.getUrlVar("fullscreen") != null) {
    console.log('creating cookie')
    var CookieSet = $.cookie('fullscreen', 'yesset', {path: '/'});
}

我也有一个快速测试,看看cookie是否存在:

if (CookieSet == null) {
   console.log('Cookie Does Not Exist');
   // redirect stuff here
} else {
   // Do not redirect 
   console.log('Get In, it Exists!');
}

所以,如果url参数存在,我就会被带到主页,这不会重定向到移动网站(是的,我知道这是一种可怕的方式,应该是响应性的-但客户希望它是这样的:(!)console.log输出:

 Get In, it Exists!

这很好。现在问题来了,当我点击页面上的另一个链接。控制台日志简短地打印出:Get In, it Exists!但很快重定向到移动网站。它不应该这样做。

有谁知道为什么cookie被发现了,然后又被忽略了吗?

也许你需要检查你的实际cookie,而不仅仅是如果CookieSet存在(==null)?

if (($.cookie('fullscreen')!=null) {
   console.log('Cookie Does Not Exist');
   // redirect stuff here
} else {
   // Do not redirect 
   console.log('Get In, it Exists!');
}

不妨看看这个:http://www.electrictoolbox.com/jquery-cookies/