javascript读写cookie的方法代码

jackxiang 2008-4-22 09:28 | |
IE浏览器里输入:javascript.document.cookie="name=xiangdong"
chrome里读取:
console.log(document.cookie)
language1=zh; uin=7srsOd27A3NlR3MU5LVzWg%3D%3D
chrome里设置:
document.cookie="name=xiangdong"
"name=xiangdong"
console.log(document.cookie)
name=xiangdong; language1=zh; uin=7srsOd27A3NlR3MU5LVzWg%3D%3D
===============================================
<script langrage=javascript>
// writeCookie("myCookie", "my name", 24);
// Stores the string "my name" in the cookie "myCookie" which expires after 24 hours.
// The hours parameter is optional; if hours is left out, the cookie value expires at the end of the visitor's browser session.
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;
}

// Example:
// alert( readCookie("myCookie") );

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;
}
</script>
<body>
<script>
writeCookie("name","xiangdong2",24);
alert( readCookie("name") );
</script>
</body>

作者:jackxiang@向东博客 专注WEB应用 构架之美 --- 构架之美,在于尽态极妍 | 应用之美,在于药到病除
地址:https://jackxiang.com/post/1016/
版权所有。转载时必须以链接形式注明作者和原始出处及本声明!


最后编辑: jackxiang 编辑于2016-11-3 11:01
评论列表
发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]