前言:工作中遇到需要在页面初始化的时候生成一个userId,然后存储在本地,当每次发出请求的时候以cookie的形式带上
相关博客链接>>
我第一想到的是将生成的使用localstorage去存储userId,然后在请求之前将userId取出来存到cookie中,但是仔细一想,何不直接存到cookie中,然后设置一下过期时间和path,而且localstorage在苹果手机上的支持也不是很好
有了想法,那就撸它。。。
于是我这样写:
1 2 3
|
document.cookie = 'userId=btm' + (Date.now() + Math.random())+';path=/test/st';
|
假设你要请求的网站是www.test.com每次请求的文件路径是不同,而想请求该网站下的不同文件时都能带上同一个cookie,只需将cookie的**path**设置为**'/'**,这样,同域名下不同路径的请求都会带上
同时也得给手动埋的cookie设置一下过期时间,要不然有些浏览器会默认cookie的过期时间为会话结束
所以,正确的写法是这样的:
1 2 3 4
| var exp = new Date(); exp.setTime(exp.getTime() + 30 * 24 * 60 * 60 * 1000); document.cookie = 'userId=btm' + (Date.now() + Math.random())+';expires='+exp.toGMTString()+';path=/';
|
对cookie方法进行封装:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| var cookie = { set:function(key,val,time){ var date=new Date(); var expiresDays=time; date.setTime(date.getTime()+expiresDays*24*3600*1000); document.cookie=key + "=" + val +";expires="+date.toGMTString(); }, get:function(key){ var getCookie = document.cookie.replace(/[ ]/g,""); var arrCookie = getCookie.split(";") var tips; for(var i=0;i<arrCookie.length;i++){ var arr=arrCookie[i].split("="); if(key==arr[0]){ tips=arr[1]; break; } }, delete:function(key){ var date = new Date(); date.setTime(date.getTime()-10000); document.cookie = key + "=v; expires =" +date.toGMTString(); } return tips; } }
|