cookie了解

cookie的特点

1.只能使用文本
2 单条存储有大小限制 4KB
3 数量限制(一般浏览器,限制大概在50条左右)
4 读取有域名限制 不可跨域读取,只能由来自 写入cookie的 同一域名 的网页可进行读取。
5 时效限制 每个cookie都有时效,最短的有效期是,会话级别:就是当浏览器关闭,那么cookie立即销毁

JavaScript 可以用 document.cookie 属性创建修改、读取、删除 cookie。

1、通过 JavaScript,可以这样创建修改 cookie:

document.cookie = "username=xiaobai";

2、添加有效日期(UTC 时间)。默认情况下,在浏览器关闭时会删除 cookie:

cont d = new Date()
document.cookie = "username=xiaobai;expires=" + d;

3、通过 path 参数,您可以告诉浏览器 cookie 属于什么路径。默认情况下,cookie 属于当前页:

cont d = new Date()
document.cookie = "username=xiaobai;expires=" + d + ";path=/";

4、通过 JavaScript,可以这样读取 cookies:

var ck = document.cookie

5、通过 JavaScript 删除 cookie:

删除 cookie 时不必指定 cookie 值, 直接把 expires 参数设置为过去的日期即可:

document.cookie = "username=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/";
练习

设置cookie函数

function setCookie (cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime + (exdays * 24 * 60 * 60 * 1000))
  var expires = "expires" + d.toUTCString();
  document.cookie = cname + "=" cvalue + ";" + expires + ";path=/"
}

获取 cookie 的函数

function getCookie (cname) {
  var name = cname + "=";
  var decodeCookie = decodeURIComponent(document.cookie);
  var ca = decodeCookie.split(";");
  for (let i = 0; i<ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') { // 清楚前面空格
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) { // 找到对象
      return c.substring(name.length, c.length); // 截取对象
    }
  }
  return "";
}

检测 cookie 的函数

function checkCookie() {
    var username = getCookie("username");
    if (username != "") {
        alert("Welcome again " + username);
    } else {
        username = prompt("Please enter your name:", "");
        if (username != "" && username != null) {
            setCookie("username", username, 365);
        }
    }
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值