转: js操作cookie

cookie的几个概念

http://dearhappyfish.blog.163.com/blog/static/1901094152012422114753777/

js操作cookie

转:http://www.oschina.net/code/snippet_156736_4923

  1 <script language=javascript> 

  2  

  3 //获得coolie 的值

  4  

  5   

  6  

  7 function cookie(name){    

  8  

  9    var cookieArray=document.cookie.split("; "); //得到分割的cookie名值对    

 10  

 11    var cookie=new Object();    

 12  

 13    for (var i=0;i<cookieArray.length;i++){    

 14  

 15       var arr=cookieArray[i].split("=");       //将名和值分开    

 16  

 17       if(arr[0]==name)return unescape(arr[1]); //如果是指定的cookie,则返回它的值    

 18  

 19    } 

 20  

 21    return ""; 

 22  

 23 } 

 24  

 25   

 26  

 27 function delCookie(name)//删除cookie

 28  

 29 {

 30  

 31    document.cookie = name+"=;expires="+(new Date(0)).toGMTString();

 32  

 33 }

 34  

 35   

 36  

 37 function getCookie(objName){//获取指定名称的cookie的值

 38  

 39     var arrStr = document.cookie.split("; ");

 40  

 41     for(var i = 0;i < arrStr.length;i ++){

 42  

 43         var temp = arrStr[i].split("=");

 44  

 45         if(temp[0] == objName) return unescape(temp[1]);

 46  

 47    } 

 48  

 49 }

 50  

 51   

 52  

 53 function addCookie(objName,objValue,objHours){      //添加cookie

 54  

 55     var str = objName + "=" + escape(objValue);

 56  

 57     if(objHours > 0){                               //为时不设定过期时间,浏览器关闭时cookie自动消失

 58  

 59         var date = new Date();

 60  

 61         var ms = objHours*3600*1000;

 62  

 63         date.setTime(date.getTime() + ms);

 64  

 65         str += "; expires=" + date.toGMTString();

 66  

 67    }

 68  

 69    document.cookie = str;

 70  

 71 }

 72  

 73   

 74  

 75 function SetCookie(name,value)//两个参数,一个是cookie的名子,一个是值

 76  

 77 {

 78  

 79     var Days = 30; //此 cookie 将被保存 30 天

 80  

 81     var exp = new Date();    //new Date("December 31, 9998");

 82  

 83     exp.setTime(exp.getTime() + Days*24*60*60*1000);

 84  

 85     document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();

 86  

 87 }

 88  

 89 function getCookie(name)//取cookies函数        

 90  

 91 {

 92  

 93     var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));

 94  

 95      if(arr != null) return unescape(arr[2]); return null;

 96  

 97   

 98  

 99 }

100  

101 function delCookie(name)//删除cookie

102  

103 {

104  

105     var exp = new Date();

106  

107     exp.setTime(exp.getTime() - 1);

108  

109     var cval=getCookie(name);

110  

111     if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();

112  

113 }

114  

115 </script>

你可能感兴趣的:(cookie)