首页 > 代码库 > cookie知识点简点

cookie知识点简点

cookie几大作用

1.保持用户登陆状态

2.跟踪用户行为

3.制定页面

4.创建购物车
cookie缺点:

1. 可能被禁用

2.可能被删除:cookie是一个文件,容易被用户删除

3.安全性不高

4.cookie可能与浏览器相关


设置cookie
     document.cookie = "userId = 100";
     alert(document.cookie);

设置多个值:
     document.cookie ="userId = 100;userPass = 23256";
     alert(document.cookie);

由于在设置多个Cookie时,它获取的是全部的cookie。而不能获取指定cookie的名称的值,所以用下面的代码实现:

Document.cookie=“userld = 100”;
Document.cookie = “passWord = 123456”;
Var strCookie = document.cookie;
Var arrCookie = strCookie.split(‘;’);
Var userId;
For(var I = 0; i< arrCookie.length; i++) {
Var arr = arrCookie.split(‘=‘);
If(‘userId’ == arr[0]) {
userId = arr[1];
Break;
}
}
Alert(userId);


Cookie设置终止日期
          var date = new Date();
          var stopDays = 0.1;
          date.setTime(date.getTime() + stopDays*24*3600*1000);
          document.cookie = "userId = 100;userName = 123456;stop = "+date.toGMTString();
          alert(document.cookie);


删除Cookie:  主要是在设置终止日期的基础上减去一个时间就行了
          // function deleteCookie(name) {
          //      var date = new Date();
          //      date.setTime(date.getTime() - 100000);
          //      document.cookie = name + "= afd; expires = " + date.toGMTString();
          //      return document.cookie;
          // }
          // alert(deleteCookie("chen"));


设置Cookie的访问路径
Document.cookie = “userId = 100; path = /one”;
表示只能在one目录下使用

使用domain = 参数设置cookie的访问主机名
Document.cookie = “ userId = 100; domain = .google.com”;
这表示所有的google.com下的所有主机都可以访问Cookie

添加cookie的通用函数
Function addCookie(name, value, expiresHours) {
Var cookieString = name + “=” + escape(value);
If(expiresHours > 0) {
Var date = new Date();
Date.setTime(date.getTime() + expirsHours * 3600 * 1000);
cookieString = cookieString +”; expires = “ + date.toGMTString();
}
Document.cookie = cookieString;
Return document.cookie;
}

指定Cookie值:getCookie(name)
function getCookie(name) {
     var strCookie = document.cookie;
     var arrCookie = strCookie.split(";");
     for (var i = 0; i < arrCookie.length; i++) {
          var arr = arrCookie[i].split("=");
          if (arr[0] == name) {
               return arr[1];
          };
     };
     return arr[1];
}

删除Cookie:deleteCookie(name)
function deleteCookie(name) {
     var date = new Date();
     date.setTime(date.getTime() - 100000);
     document.cookie = name + "= afd; expires = " + date.toGMTString();
     return document.cookie;
}