为啥JS的cookie读取不到
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为啥JS的cookie读取不到相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<input type="button" value="set" onclick="set('me')">
<input type="button" value="get" onclick="get()">
</body>
</html>
<script>
function set(name)
var date = new Date();
date.setTime(date.getTime() + 1000*1800);
var str = name + "=" + escape("helloword") + ";expires=" + date.toGMTString();
document.cookie = str;
alert(str);
alert(document.cookie.length);
function get()
alert(document.cookie);
</script>
此时调用document.cookie.length结果为0,证明没有cookie,为什么
我在CHROME下测试是可以得到的,本回答被提问者采纳
读取Cookie时总是空的,为啥
public static string GetCartGUID()
HttpCookie cartid = HttpContext.Current.Request.Cookies["LittleItalyVineyard"];
//如果Cookie已存在
if (cartid != null)
return cartid.Values["CartID"];
else
//生成一个标识符
Guid CartGUID = Guid.NewGuid();
//定义一个新Cookie
HttpCookie cookie = new HttpCookie("LittleItalyVineyard");
//键值对赋值
cookie.Values.Add("CartID", CartGUID.ToString());
//定义过期时间
cookie.Expires = DateTime.Now.AddDays(30);
//添加Cookie到
HttpContext.Current.Response.AppendCookie(cookie);
return CartGUID.ToString();
每次调用上面这个方法时,判断cartid都是空,为什么,求解
浏览器没有禁用cookie,Temporary Interneet Files文件下有文件,并且里面有内容,有CartID的值,但是读取时还是空的 ,在这个页面调用这个方法时cartid为空,于是重新创建一个cookie,再到另一个页面调用这个方法时,cartid还是空 .使用6楼的方法仍然为空。把浏览器的隐私设置调整了也是空
注意吧Path 和Domain 都添加上看看
————
应该是Domain 的问题,在设置的时候原则上是
www.aa.com,包含www.aa.com/aa的,但是www.aa.com/是无法访问
www.aa.com/aa的
有点绕,
kid83说的也有道理,Page.Response处理当前页,Current.Response处理当前对象
但是同一个页应该一样。
要不你把东西发上来看看 参考技术A 贴上代码,读取是空的,要么就是读取的东西没有赋值,要么就是读取的字段名搞错了。 参考技术B 原因估计出在这
Guid CartGUID = Guid.NewGuid();或者Guid CartGUID = Guid.NewGuid().ToString();
CartGUID估计没有获得值,你可以换个值看看是否为空。 参考技术C 浏览器是不是禁用了Cookie 参考技术D cookie.Expires = DateTime.Now.AddDays(30);
Response.SetCookie(cookie);
以上是关于为啥JS的cookie读取不到的主要内容,如果未能解决你的问题,请参考以下文章