检查cookie是否存在cookie

检查cookie是否存在的好方法是什么?

条件:

cookie1=;cookie1=345534;

//or

cookie1=345534;cookie1=;

//or

cookie1=345534;

cookie=;

//or

<blank>

回答:

您可以使用所需cookie的名称调用函数getCookie,然后检查其是否为null。

function getCookie(name) {

var dc = document.cookie;

var prefix = name + "=";

var begin = dc.indexOf("; " + prefix);

if (begin == -1) {

begin = dc.indexOf(prefix);

if (begin != 0) return null;

}

else

{

begin += 2;

var end = document.cookie.indexOf(";", begin);

if (end == -1) {

end = dc.length;

}

}

// because unescape has been deprecated, replaced with decodeURI

//return unescape(dc.substring(begin + prefix.length, end));

return decodeURI(dc.substring(begin + prefix.length, end));

}

function doSomething() {

var myCookie = getCookie("MyCookie");

if (myCookie == null) {

// do cookie doesn't exist stuff;

}

else {

// do cookie exists stuff

}

}

以上是 检查cookie是否存在cookie 的全部内容, 来源链接: utcz.com/qa/420565.html

回到顶部