如何使用js来获取cookie的值
2个回答
推荐于2017-10-06
展开全部
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="keywords" content="白菜编辑部">
<title>白菜编辑部</title>
<style type="text/css">
</style>
<script type="text/javascript">
function readCookie (name)
{
var cookieValue = "";
var search = name + "=";
if (document.cookie.length > 0)
{
offset = document.cookie.indexOf (search);
if (offset != -1)
{
offset += search.length;
end = document.cookie.indexOf (";", offset);
if (end == -1)
end = document.cookie.length;
cookieValue = unescape (document.cookie.substring (offset, end))
}
}
return cookieValue;
}
function writeCookie (name, value, hours)
{
var expire = "";
if (hours != null)
{
expire = new Date ((new Date ()).getTime () + hours * 3600000);
expire = "; expires=" + expire.toGMTString ();
}
document.cookie = name + "=" + escape (value) + expire;
}
writeCookie ("myCookie", "my name", 24);
alert (readCookie ("myCookie"));
</script>
</head>
<body>
</body>
</html>
展开全部
function getCookie(cookie_name){var allcookies = document.cookie;var cookie_pos = allcookies.indexOf(cookie_name); //索引的长度 // 如果找到了索引,就代表cookie存在,// 反之,就说明不存在。if (cookie_pos != -1){// 把cookie_pos放在值的开始,只要给值加1即可。cookie_pos += cookie_name.length + 1; //这里我自己试过,容易出问题,所以请大家参考的时候自己好好研究一下。。。var cookie_end = allcookies.indexOf(";", cookie_pos); if (cookie_end == -1){cookie_end = allcookies.length;} var value = unescape(allcookies.substring(cookie_pos, cookie_end)); //这里就可以得到你想要的cookie的值了。。。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询