Javascript 检查 cookie 是否存在不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33203120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if cookie exists not working
提问by Mina Hafzalla
I'm using the below code to check if a cookie exists with a certain value then do something.
我正在使用以下代码来检查是否存在具有特定值的 cookie,然后执行某些操作。
$(document).ready(function() {
if (document.cookie.indexOf('samplename=itsvalue')== -1 ) {
alert("cookie");
}
});
It always displays the alert whether the cookie exists or not. What I'm doing wrong here?
无论 cookie 是否存在,它始终显示警报。我在这里做错了什么?
回答by buzzsaw
Original response:
原回复:
Unless you have a cookie with the key "samplename=itsvalue", your code will always evaluate to true. If the key is "samplename" and the value is "itsvalue", you should rewrite the check like this:
除非您有一个带有“samplename=itsvalue”键的 cookie,否则您的代码将始终评估为 true。如果键是“samplename”,值是“itsvalue”,你应该像这样重写检查:
if (document.cookie.indexOf('samplename') == -1 ) {
alert("cookie");
}
This will tell you that the cookie does not exist.
这将告诉您 cookie 不存在。
To see if it does exist:
要查看它是否确实存在:
if (document.cookie.indexOf('samplename') > -1 ) {
alert("cookie exists");
}
Updating to better address this question:
更新以更好地解决此问题:
What you are looking for in that check will always evaluate to true and throw the alert. Add the following function to your js and call it to check if your cookie exists.
您在该检查中查找的内容将始终评估为 true 并发出警报。将以下函数添加到您的 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));
}
You can then check your cookies with the following:
然后,您可以使用以下方法检查您的 cookie:
var myCookie = getCookie("samplename");
if (myCookie == null) {
alert("cookie does not exist");
} else {
alert("cookie exists");
}
回答by abhiagNitk
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");
}
Paste this code in browser console and check.
将此代码粘贴到浏览器控制台中并检查。