DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> JavaScript設置、獲取、清除單值和多值cookie的方法
JavaScript設置、獲取、清除單值和多值cookie的方法
編輯:關於JavaScript     

廢話不多說了,直接給大家貼代碼了。

具體代碼如下:

var CookieUtil = (function () {
   var Cookie = function () {
     // 獲取單值cookie
     this.get = function(name) {
       var start = document.cookie.indexOf(encodeURIComponent(name)) ;
       var end = document.cookie.indexOf(';', start) ;
       if(end == -) {
         end = document.cookie.length;
       }
       return decodeURIComponent(document.cookie.substring(start+name.length+,end));
     };
     // 設置單值cookie
     this.set = function(name, value, expires, path, domain, secure) {
       var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
       // 設置默認過期時間為七天
       if(expires == undefined) {
         var date = new Date();
         date.setTime(date.getTime() + ****);
         expires = date ;
       }
       if(expires instanceof Date) {
         cookieText += "; expires=" + expires.toGMTString();
       }
       if(path != undefined) {
         cookieText += "; path=" + path;
       }
       if(domain != undefined) {
         cookieText += "; domain" + domain;
       }
       if(secure != undefined) {
         cookieText += "; secure";
       }
       document.cookie = cookieText;
     };
     // 清除單值cookie
     this.unset = function(name, path, domain, secure) {
       this.set(name, '', new Date(), path, domain, secure );
     };
     // 設置多值cookie
     this.setAll = function(name, subCookies, expires, path, domain, secure) {
       var cookieText = ";" + encodeURIComponent(name) + "=",
       arr = new Array();
       for(var attr in subCookies) {
         arr.push([encodeURIComponent(attr)] + ":" + encodeURIComponent(subCookies[attr]));
       } 
       this.set(name, arr.join('&'), expires, path, domain, secure);
     };
     // 獲取多值cookie
     this.getAll = function(name) {
       var obj = {};
       var arr = this.get(name).split('&');
       for(var i = , len = arr.length; i < len; i++) {
         var tmpArr = arr[i].split(':');
         obj[decodeURIComponent(tmpArr[])] = decodeURIComponent(tmpArr[]);
       }
       return obj;
     };
     // 獲取多值cookie的子cookie
     this.getSub = function(name, subname) {
       var obj = this.getAll(name);
       return obj[subname];
     };
     // 清除指定的多值cookie
     this.unsetAll = function(name,path,domain,secure) {
       this.unset(name, '', new Date(), path, domain, secure);
     };
     // 清除指定多值cookie的子cookie
     this.unsetSub = function(name, subname,path, domain, secure) {
       var obj = this.getAll(name);
       delete obj[subname];
       this.setAll(name, obj, null, path, domain, secure);
     };
   };
   return new Cookie();
 })();

 以上代碼就是本文給大家介紹JavaScript設置、獲取、清除單值和多值cookie的方法,有哪裡不清楚的地方歡迎給我留言。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved