2016-07-14 118 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; 

}