首页 > 代码库 > cookie的使用

cookie的使用

 1 //cookie部分
 2 //设置cookie
 3 //注意cname传入字符串类型,如:setCookie(‘first‘);
 4 function setCookie(cname,cvalue,exdays){
 5     var d = new Date();
 6     d.setTime(d.getTime()+(exdays*24*60*60*1000));
 7     var expires = "expires="+d.toGMTString();
 8     document.cookie = cname+"="+cvalue+"; "+expires;
 9 }
10 //获取cookie
11 function getCookie(cname){
12     var name = cname + "=";
13     var ca = document.cookie.split(‘;‘);
14     for(var i=0; i<ca.length; i++) {
15         var c = ca[i].trim();
16         if (c.indexOf(name)==0) return c.substring(name.length,c.length);
17     }
18     return "";
19 }
20 //检查cookie
21 function checkCookie(){
22     var user=getCookie("username");
23     if (user!=""){
24         alert("Welcome again " + user);
25     }
26     else {
27         user = prompt("Please enter your name:","");
28         if (user!="" && user!=null){
29             setCookie("username",user,30);
30         }
31     }
32 }
33 //删除单个cookie
34 function clearCookie(name) {
35     setCookie(name, "", -1);
36 }
37 //删除所有cookie
38 function clearAllCookie(){
39     var keys=document.cookie.match(/[^ =;]+(?=\=)/g);
40     if (keys) {
41         for (var i =  keys.length; i--;)
42             document.cookie=keys[i]+‘=0;expires=‘ + new Date( 0).toUTCString()
43     }
44 }

 

cookie的使用