JS操作Cookie

版权声明:本文为博主原创文章,转载请标明出处。 https://blog.csdn.net/jianggujin/article/details/80729637

通常我们会在HTML页面中,使用Cookie存储一些临时数据,所以封装了两个方法用于Cookie的便捷操作,代码如下:

/**
  * cookie操作
  * @param {String} name
  * @param {String} value
  * @param {JSON} options
  */
function cookie(name, value, options) {
   // 写
   if(arguments.length > 1) {
      options = options || {};

      if(typeof options.expires === 'number') {
         var days = options.expires,
            t = options.expires = new Date();
         t.setMilliseconds(t.getMilliseconds() + days * 864e+5);
      }

      return(document.cookie = [
         name, '=', value,
         options.expires ? '; expires=' + options.expires.toUTCString() : '', 
         //使用expires属性, max-age不支持IE
         options.path ? '; path=' + options.path : '',
         options.domain ? '; domain=' + options.domain : '',
         options.secure ? '; secure' : ''
      ].join(''));
   }

   // 读取
   var arr = document.cookie.replace(/\s/g, "").split(';');
   for(var i = 0; i < arr.length; i++) {
      var tempArr = arr[i].split('=');
      if(tempArr[0] == name) {
         return tempArr[1];
      }
   }
   return undefined;
}
function removeCookie(name) {
   cookie(name, '', {
      expires: -1
   });
   return !cookie(name);
}
阅读更多

扫码向博主提问

蒋固金

非学,无以致疑;非问,无以广识
  • 擅长领域:
  • java
  • oracle
  • js
去开通我的Chat快问

js操作cookie的疑惑

01-06

[code=JScript]function Cookie(name)rn this.$name = name; rn var allcookies = document.cookie;rn if(allcookies == "")return;rn var cookies = allcookies.split(";");rn var cookie = null;rn for(var i = 0; i < cookies.length; i++)rn // Does this cookie string begin with the name we want?rn if (cookies[i].substring(0, name.length+1) == (name + "="))rn cookie = cookies[i];rn break;rn rn rn if (cookie == null) return;rn var cookieval = cookie.substring(name.length+1);rn var a = cookieval.split("&");rn for(var i=0; i < a.length; i++)rn a[i] = a[i].split(":");rn rn for(var i=0; i < a.length; i++)rn this[a[i][0]] = decodeURIComponent(a[i][1]);rn rn rn/**rn* This function is the store() method of the Cookie object.rn*rn* Arguments:rn*rn* daysToLive: the lifetime of the cookie, in days. If you set thisrn* to zero, the cookie will be deleted. If you set it to null, orrn* omit this argument, the cookie will be a session cookie and willrn* not be retained when the browser exits. This argument is used torn* set the max-age attribute of the cookie.rn* path: the value of the path attribute of the cookiern* domain: the value of the domain attribute of the cookiern* secure: if true, the secure attribute of the cookie will be setrn*/ rn Cookie.prototype.store = function(daysToLive, path, domain, secure)rn var cookieval = "";rn for(var prop in this)rn if ((prop.charAt(0) == "$") || ((typeof this[prop]) == "function"))rn continue;rn if (cookieval != "") cookieval += "&";rn cookieval += prop + ":" + encodeURIComponent(this[prop]);rn rn var cookie = this.$name + "=" + cookieval;rn if (daysToLive || daysToLive == 0)rn cookie += "; max-age=" + (daysToLive*24*60*60);rn rn if (path) cookie += "; path=" + path;rn if (domain) cookie += "; domain=" + domain;rn if (secure) cookie += "; secure";rn rn document.cookie = cookie;rn ;rn rn/**rn* This function is the remove() method of the Cookie object; it deletes thern* properties of the object and removes the cookie from the browser'srn* local store.rn*rn* The arguments to this function are all optional, but to remove a cookiern* you must pass the same value you passed to store().rn*/rn Cookie.prototype.remove = function(path,domain, secure)rn for(var prop in this)rn if (prop.charAt(0) != "$" && typeof this[prop] != "function")rn delete this[prop];rn rn this.store(0,path,domain,secure);rn ;rn rn/**rn* This static method attempts to determine whether cookies are enabled.rn* It returns true if they appear to be enabled and false otherwise.rn* A return value of true does not guarantee that cookies actually persist .rn* Nonpersistent session cookies may still work even if this methodrn* return false.rn*/rn Cookie.enabled = function()rn if (navigator.cookieEnabled != undefined) return navigator.cookieEnabled;rn if (Cookie.enabled.cache != undefined) return Cookie.enabled.cache;rn document.cookie = "testcookie=test; max-age=10000";rn var cookies = document.cookie;rn if (cookies.indexOf("testcookie=test") == -1)rn return Cookie.enable.cache = false;rn rn elsern document.cookie = "testcookie=test; max-age=0";rn return Cookie.enable.cache = true;rn rn ;[/code]rnrn上面是从js权威指南上摘抄下来的代码rnrn按照代码 , 我是这样操作的cookie rn[code=JScript]rn var cookie=new Cookie('docman'); rn cookie.close=1;rn cookie.store(1,"/");rn[/code]rn这样的话 我只要在同意域名下,就能读取到这个cookie,但是 我只要离开设置cookie的页面就读取不到了 rnrn求解 , 我用的是火狐和google的浏览器 。。。。。rn可能是我水平实在有限rn望高人指教

关于js操作cookie的问题

09-07

是这样,我现在正在用MVC做一个购物车的作业,要求写入cookiern在商品的Controllers中写入了,这个Controllers里面所有的action都可以正常读取出来,可是换了购物车的Controllers,就读不出来了。请高手帮帮忙~谢谢rnjs代码如下:rn[code=JScript]rn/向购物车增加商品rnfunction addDressMinuteCookie(id, image, name, size, price) rn //获取购物车中的物品,并判断是否有物品rn var dressMinuteList = getCookie("ShoppingCar");rn if (dressMinuteList == null) rn var begin = "[";rn var content = "'id':'" + id + "','image':'" + image + "','name':'" + name + "','size':'" + size + "','price':'" + price + "'";rn var end = "]";rn //增加rn SetCookie("ShoppingCar", begin + content + end);rn alert("增加成功");rn rn else rn //判断购物车中是否已经有该物品rn if (checkCookieDressMinute(id, dressMinuteList)) rn var dressMinuteString = dressMinuteList.substring(0, dressMinuteList.indexOf("]", 0));rn var dressMinute = ",'id':'" + id + "','image':'" + image + "','name':'" + name + "','size':'" + size + "','price':'" + price + "']";rn SetCookie("ShoppingCar", dressMinuteString + dressMinute);rn alert("增加成功");rn rn else rn alert("您的购物车中,该物品已经存在!");rn rn rnrn//增加rnfunction SetCookie(name, value) rn var Days = 360;rn var exp = new Date();rn exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);rn document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();rnrnrn//获取JSON格式的商品信息rnfunction getCookie(cookieName) rn var allCookie = document.cookie;rn var cookiePos = allCookie.indexOf(cookieName);rn // 如果找到了索引,就代表cookie存在,rn // 反之,就说明不存在。rn if (cookiePos != -1) rn cookiePos += cookieName.length + 1;rn var cookieEnd = allCookie.indexOf(";", cookiePos);rn if (cookieEnd == -1) rn cookieEnd = allCookie.length;rn rn var value = unescape(allCookie.substring(cookiePos, cookieEnd));rn rn return value;rnrn[/code]

aspx页面js操作cookie问题

11-12

[code=JScript]function getCookieVal(offset) rn var endstr = document.cookie.indexOf (";", offset);rn if(endstr == -1) rn endstr = document.cookie.length;rn rn return unescape(document.cookie.substring(offset, endstr));rnrnfunction getCookie(name) rn var arg = name + "=";rn var alen = arg.length;rn var clen = document.cookie.length;rn var i = 0;rn var j = 0;rn while(i < clen) rn j = i + alen; rn if(document.cookie.substring(i, j) == arg)rn return getCookieVal(j);rn i = document.cookie.indexOf(" ", i) + 1;rn if(i == 0)rn break;rn rn return null;rnrnfunction deleteCookie(name)rn var exp = new Date(); rn var cval = getCookie(name); rn exp.setTime(exp.getTime() - 1); rn document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();rnrnvar gCookieExpDays = 80;rnfunction setCookie(name, value) rn var argv = setCookie.arguments;rn var argc = setCookie.arguments.length;rn var exp = (argc > 2) ? argv[2] : gCookieExpDays;rn var path = (argc > 3) ? argv[3] : null;rn var domain = (argc > 4) ? argv[4] : null;rn var secure = (argc > 5) ? argv[5] : false;rn var expires = new Date();rn deleteCookie(name);rn expires.setTime(expires.getTime() + (exp*24*60*60*1000));rn document.cookie = name + "=" + value +rn "; expires=" + expires.toGMTString() +rn ((domain == null) ? "" : ("; domain=" + domain)) +rn ((path == null) ? "" : ("; path=" + path)) +rn ((secure == true) ? "; secure" : "");rn[/code]rnrn为什么这段代码的清除cookie deleteCookie(name)在html页面执行正常,在aspx页面死活清除不掉呢?

没有更多推荐了,返回首页