cookie
cookie
- 服务器用来在客户端存储一些数据,比如用户信息
- 量小 4kb
- 1-设置cookie
document.cookie = "username=aaa"; document.cookie = "pass=123"; var date = new Date(); date.setSeconds(date.getSeconds() + 10); //设置cookie 及过期时间 //document.cookie = "username=aaa;expires=" + date; 封装设置cookie方法: function setCookie(cName, cValue, day) { var date = new Date(); date.setDate(date.getDate() + day); document.cookie = cName + '=' + cValue + ';expires=' + date; } setCookie('username', 'aaa', 1); setCookie('pass', '123', 1);
- 2-获取cookie
var c = document.cookie; console.log(c); //'username=aaa; pass=123' 封装获取cookie的方法: function getCookie(cName) { var cookieObj = {}; var cstring = document.cookie; //'username=aaa; pass=123; city=bbb' --> {username:aaa,pass:123} var ary = cstring.split('; '); //['username=aaa','pass=123'] for (var i = 0; i < ary.length; i++) { var ary1 = ary[i].split('='); cookieObj[ary1[0]] = ary1[1]; } return cookieObj[cName]; } var v = getCookie('pass'); console.log(v);
- 3-删除cookie
/* 删除cookie :原理就是把过期时间设置为前一天*/ function removeCookie(cName) { setCookie(cName, 1, -1); } removeCookie('username');
参考资料: https://www.cnblogs.com/bq-med/p/8603664.html