浏览器cookie那些事儿

 
1、介绍
①什么是cookie
  • 页面用来保存信息
--比如,自动登录,记住用户名等
  • cookie的特性
--同一个网站中所有页面共享一套cookie
--数量大小有限
--过期时间
  • js中使用cookie
document.cookie
②cookie的使用
  • 设置cookie
--格式 :名字=值
--不会覆盖
--过期时间:expires=时间(如果没有指定过期时间,默认浏览器窗口关闭过期)
>>日期对象使用
--封装函数
1 //设置存cookie
2             //时间以毫秒为单位,请记得换算好时间哦(1秒=1000,1分钟=60*1000)
3             function setCookie(sname, svalue, stime) {
4                 var sdate = new Date();
5                 sdate.setTime(sdate.getTime() + stime);
6                 document.cookie = sname + "=" + svalue + ";expires=" + sdate.toGMTString();
7 
8             }
  • 读取cookie
--字符串分割
 1 //读取cookie
 2             function getCookie(sname) { //获取单个cookies
 3                 var acookie = document.cookie.split("; ");
 4                 for (var i = 0; i < acookie.length; i++) {
 5                     var arr = acookie[i].split("=");
 6                     if (sname == arr[0]) {
 7                         if (arr.length > 1)
 8                         //unescape() 函数可对通过 escape() 编码的字符串进行解码。
 9                         //decodeURIComponent() 函数可对 encodeURIComponent() 函数编码的 URI 进行解码。
10                         //decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码。
11                         //ECMAScript v3 已从标准中删除了 unescape() 函数,并反对使用它,因此应该用 decodeURI() 和 decodeURIComponent() 取而代之。
12                             return decodeURIComponent(arr[1]);
13                         else
14                             return "";
15                     }
16                 }
17                 return "";
18             }
  • 删除cookie
--已经过期
1 //删除cookie
2             function deleteCookie(dname) {
3                 var date = new Date();
4                 date.setDate(date.getDate() - 1);
5                 var dvalue = getCookie(dname);
6                 document.cookie = dname + '=' + dvalue + ';expires=' + date;
7             }

提示:cookie在服务器上能正常使用,如果想在本地测试cookie,请选择火狐浏览器,可以查看到自己存的cookie哦。

2、你可能会遇到的问题---中文乱码

先后台(这里用到的是Java)编码

Cookie cookie = new Cookie("User",URLEncoder.encode(username,"utf-8"));

后前台js解码

var username = decodeURI(username);

3、cookie的利弊(借鉴)

这个博主对cookie写的比较详细可以参考一下下。

http://www.cnblogs.com/Heaven1020/p/5361711.html

有啥不足或者意见建议, 留言补充哦,谢谢。

 

原文地址:https://www.cnblogs.com/youxiaowei/p/youxiaowei.html