JS设置获取cookies

结合JavaScript权威指南,加上项目开发时在网上搜集的资料,整理了两种设置和获取cookie的方法。

<script>

//设置cookie  方法一
function setCookie(name,value){ 
  var exp = new Date(); 
  exp.setTime(exp.getTime() + 1*60*60*1000);//有效期1小时 
  document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); 
}

/*存取cookie时一般要对容易注入的字符进行编码,相应的在获取cookie时要解码,编码方式有很多种,有时间的话写一篇关于编码解码的博客*/

//设置cookie 方法 二
直接存储cookie
document.cookie = "homepage = http://www.sina.com";

 /*-------------------------------------------------------------------------------------------------------*/

//取cookies函数 方法 一
function getCookie(name){

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

  if(arr != null)    

    return unescape(arr[2]);

  return null;

}

//取cookies函数  方法二

function getCookie(key){
  if(key==null)
    return null;
  if(Object.prototype.toString.call(key)=='[object String]'|| Object.prototype.toString.call(key)=='[object Number]')
  {
    var arrStr = document.cookie.split(";");
    for(var i= 0;i<arrStr.length;i++){
    var temp = arrStr[i].split("=");
    if(temp[0]==key)
      return unescape(temp[1]);
    }
    return null;
  }
  return null;
}

</script>

function setcookie(cookieName, cookieValue, seconds, path, domain, secure) {
if(cookieValue == '' || seconds < 0) {
cookieValue = '';
seconds = -2592000;
}
if(seconds) {
var expires = new Date();
expires.setTime(expires.getTime() + seconds * 1000);
}
domain = !domain ? cookiedomain : domain;
path = !path ? cookiepath : path;
document.cookie = escape(cookiepre + cookieName) + '=' + escape(cookieValue)
+ (expires ? '; expires=' + expires.toGMTString() : '')
+ (path ? '; path=' + path : '/')
+ (domain ? '; domain=' + domain : '')
+ (secure ? '; secure' : '');
}

function getcookie(name, nounescape) {
name = cookiepre + name;
var cookie_start = document.cookie.indexOf(name);
var cookie_end = document.cookie.indexOf(";", cookie_start);
if(cookie_start == -1) {
return '';
} else {
var v = document.cookie.substring(cookie_start + name.length + 1, (cookie_end > cookie_start ? cookie_end : document.cookie.length));
return !nounescape ? unescape(v) : v;
}
}

 

posted @ 2014-01-23 20:43  寻一颗心  阅读(1124)  评论(0编辑  收藏  举报