2016-07-14 36 views
0

在我的应用程序使用jQuery插件的Cookie V1.4.1(https://github.com/carhartl/jquery-cookie)这样的设置cookie:如何避免重复饼干

$.removeCookie("Test_Cookie"); 
$.cookie("Test_Cookie", "xxx"); 

我想这个cookie只存在一次,但在某些情况下的cookie存在两次。

这怎么可能,以及确保某个cookie只存在一次的最佳做法是什么?

+0

你是什么意思, “存在两次”?你有两个'Test_Cookie'饼干出现在用户的饼干罐子里? –

+0

是的。查看Fiddler的截图:http://imgur.com/WlYu987 – Palmi

+0

检查原始头文件并查看'set-cookie'是什么。如果您有两个Cookie但路径不同,则可以获得相同的名称/值,并且浏览器返回的是未定义/可变的。 –

回答

0

您可以使用String.prototype.split()document.cookie转换为一个键值数组字符串(key=value),然后您可以对它们进行迭代,将它们分开,并且如果键为值,则为break。请参阅下面的例子:

function checkCookieExists(cookieName){ 
    var cookies = document.cookie.split(';'); //returns lots of these: key=value 
    var toCheckCookie = cookieName; //checks if this cookie exists 

    cookies.forEach(function(cookie){ //foreach cookie 
    var key = cookie.split('=')[0]; //the key cookie 

    if (key.toLowerCase() === toCheckCookie) //if the current key is the toCheckCookie 
    { 
     return true; 
    } 
    }); 
    return true; 

}