2015-10-18 101 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"); 
    } 

粘贴浏览器控制台这个代码和检查。