检查cookie是否存在无效

Min*_*lla 4 javascript cookies jquery

我正在使用以下代码来检查cookie是否存在具有特定值然后执行某些操作.

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

它始终显示cookie是否存在的警报.我在这里做错了什么?

buz*_*saw 11

原始回复:

除非您的密钥为"samplename = itsvalue",否则您的代码将始终评估为true.如果键是"samplename"并且值是"itsvalue",则应该像这样重写检查:

if (document.cookie.indexOf('samplename') == -1 ) {
  alert("cookie");
}
Run Code Online (Sandbox Code Playgroud)

这将告诉您cookie不存在.

要查看它是否存在:

if (document.cookie.indexOf('samplename') > -1 ) {
  alert("cookie exists");
}
Run Code Online (Sandbox Code Playgroud)

更新以更好地解决此问题:

您在该检查中寻找的内容将始终评估为真并发出警报.将以下函数添加到您的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));
} 
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用以下内容检查您的Cookie:

var myCookie = getCookie("samplename");

if (myCookie == null) {
    alert("cookie does not exist");
} else {
    alert("cookie exists");
}
Run Code Online (Sandbox Code Playgroud)

  • @JerryB我将重新添加我之前的代码.很高兴它对你有用. (2认同)