js获取cookie值的方法
JavaScript是运行在客户端的脚本,需要用到cookie,所以可以用JS来设置cookie。那么cookie怎么设置呢?下面小编教你怎么设置cookie吧。
操作方法
- 01
首先JS设置cookie: 假设在A页面中要保存变量username的值("jack")到cookie中,key值为name,则相应的JS代码为: document.cookie="name="+username;
- 02
JS读取cookie: var username=document.cookie.split(";")[0].split("=")[1]; function setCookie(name,value) { var Days = 30; var exp = new Date(); exp.setTime(exp.getTime() + Days*24*60*60*1000); document.cookie = name +"="+ escape (value) +";expires=" + exp.toGMTString(); }
- 03
读取cookies function getCookie(name) { var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)"); if(arr=document.cookie.match(reg)) return unescape(arr[2]); else return null; }
- 04
删除cookies function delCookie(name) { var exp = new Date(); exp.setTime(exp.getTime() - 1); var cval=getCookie(name); if(cval!=null) document.cookie= name +"="+cval+";expires="+exp.toGMTString(); } setCookie("name","hayden"); alert(getCookie("name")); function setCookie(name,value,time) { var strsec = getsec(time); var exp = new Date(); exp.setTime(exp.getTime() + strsec*1); document.cookie = name +"="+ escape (value) +";expires=" + exp.toGMTString(); } function getsec(str) { alert(str); var str1=str.substring(1,str.length)*1; var str2=str.substring(0,1); if (str2=="s") { return str1*1000; } else if (str2=="h") { return str1*60*60*1000; } else if (str2=="d") { return str1*24*60*60*1000; } } setCookie("name","hayden","s20");