JS操作cookie,设置、获取、清除cookie

发布时间:2011年09月27日      浏览次数:329 次
//设置Cookie
function setCookie(name, value) {
      var argv = setCookie.arguments;
      var argc = setCookie.arguments.length;
      var exp = (argc > 2) ? argv[2] : 90;
      var path = (argc > 3) ? argv[3] : null;
      var domain = (argc > 4) ? argv[4] : null;
      var secure = (argc > 5) ? argv[5] : false;
      var expires = new Date();
      deleteCookie(name);
      expires.setTime(expires.getTime() + (exp*24*60*60*1000));
      document.cookie = name + "=" + value +
      "; expires=" + expires.toGMTString() + //如果注释该行,默认cookie有效期至浏览器关闭
      ((domain === null) ? "" : ("; domain=" + domain)) +
      ((path === null) ? "" : ("; path=" + path)) +
      ((secure === true) ? "; secure" : "");
}

//获取Cookie
function getCookie(name) {
      var arg = name + "=";
      var alen = arg.length;
      var clen = document.cookie.length;
      var i = 0;
      var j = 0;
      while(i < clen) {
            j = i + alen;
            if(document.cookie.substring(i, j) == arg){
                  return getCookieval_r(j);
            }
            i = document.cookie.indexOf(" ", i) + 1;
            if(i === 0){
                  break;
            }
      }
      return '';
}

//删除Cookie
function deleteCookie(name) {
      var exp = new Date();
      var cval = getCookie(name);
      exp.setTime(exp.getTime() - 1);
      document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}

//获取Cookie时,函数内部调用的函数
function getCookieval_r(offset) {
      var endstr = document.cookie.indexOf(";", offset);
      if(endstr == -1) {
            endstr = document.cookie.length;
      }
      return document.cookie.substring(offset, endstr);
}
免责声明:本站相关技术文章信息部分来自网络,目的主要是传播更多信息,如果您认为本站的某些信息侵犯了您的版权,请与我们联系,我们会即时妥善的处理,谢谢合作!