JavaScript是运行在客户端的脚本,需要用到cookie,所以可以用JS来设置cookie。那么cookie怎么设置呢?下面小编教你怎么设置cookie吧。
方法/步骤
1、首先JS设置cookie:假设在A页面中要保存变量username的值("jack")到cookie中,key值为name,则相应的JS代码为:document.cookie="name="+username;
2、JS读取cookie:varusername=document.cookie.split(";")[0].split("=")[1];functionsetCookie(name,value){varDays=30;varexp=newDate();exp.setTime(exp.getTime()+Days*24*60*60*1000);document.cookie=name+"="+escape(value)+";expires="+exp.toGMTString();}
3、读取cookiesfunctiongetCookie(name){vararr,reg=newRegExp("(^|)"+name+"=([^;]*)(;|$)");if(arr=document.cookie.match(reg))returnunescape(arr[2]);elsereturnnull;}
4、删浑睡蔽嗍除cookiesfunctiondelCookie(name){varexp=newDate();ex禊诬娱飑p.setTime(exp.getTime()-1);varcval=getCookie(name);if(cval!=null)document.cookie=name+"="+cval+";expires="+exp.toGMTString();}setCookie("name","hayden");alert(getCookie("name"));functionsetCookie(name,value,time){varstrsec=getsec(time);varexp=newDate();exp.setTime(exp.getTime()+strsec*1);document.cookie=name+"="+escape(value)+";expires="+exp.toGMTString();}functiongetsec(str){alert(str);varstr1=str.substring(1,str.length)*1;varstr2=str.substring(0,1);if(str2=="s"){returnstr1*1000;}elseif(str2=="h"){returnstr1*60*60*1000;}elseif(str2=="d"){returnstr1*24*60*60*1000;}}setCookie("name","hayden","s20");