2015-10-18 96 views
3

我正在使用下面的代碼來檢查cookie是否存在某個值,然後執行某些操作。檢查cookie是否存在不工作

$(document).ready(function() { 
    if (document.cookie.indexOf('samplename=itsvalue')== -1) { 
     alert("cookie"); 
    } 
}); 

它始終顯示cookie是否存在的警報。我在這裏做錯了什麼?

回答

8

原始響應:

除非你有鑰匙 「samplename = itsvalue」 一個cookie,你的代碼將始終爲true。如果關鍵是「samplename」和值是「itsvalue」,你應該重寫檢查這樣的:

if (document.cookie.indexOf('samplename') == -1) { 
    alert("cookie"); 
} 

這會告訴你該Cookie不存在。

要看看它存在:

if (document.cookie.indexOf('samplename') > -1) { 
    alert("cookie exists"); 
} 

更新,以更好地解決這個問題:

什麼您正在尋找在檢查將始終評估爲真並引發警報。將以下函數添加到您的js並調用它來檢查您的cookie是否存在。

function getCookie(name) { 
    var cookie = document.cookie; 
    var prefix = name + "="; 
    var begin = cookie.indexOf("; " + prefix); 
    if (begin == -1) { 
     begin = cookie.indexOf(prefix); 
     if (begin != 0) return null; 
    } else { 
     begin += 2; 
     var end = document.cookie.indexOf(";", begin); 
     if (end == -1) { 
     end = cookie.length; 
     } 
    } 
    return unescape(cookie.substring(begin + prefix.length, end)); 
} 

你可以接着用下面的檢查你的餅乾:

var myCookie = getCookie("samplename"); 

if (myCookie == null) { 
    alert("cookie does not exist"); 
} else { 
    alert("cookie exists"); 
} 
+1

謝謝您的回答和更新!對此,我真的非常感激。我測試了你以前的代碼(更新之前),它的工作很完美,所以再次感謝你。我會以此爲接受的答案,因爲它解決了我的問題。如果您將新的代碼重新添加到新的代碼中,作爲替代解決方案來解決具有相同問題的任何人,也許會很好。這裏是'if(document.cookie.indexOf('samplename')> -1){alert(「cookie」); '問候! –

+2

@JerryB我會將我以前的代碼添加回來。很高興爲您工作。 – buzzsaw

+0

'dc沒有定義' –

1
var cookies = document.cookie.split(';');//contains all the cookies 
var cookieName = []; // to contain name of all the cookies 

for(i=0;i<cookies.length;i++) { 
    cookieName[i] = cookies[i].split('=')[0].trim(); 
} 

    if(cookiesName.indexOf(cookieNameYouAreLookingFor)>-1) { 
     console.log("EXISTS"); 
    } else { 
     console.log("DOESN'T EXIST"); 
    } 

粘貼瀏覽器控制檯這個代碼和檢查。