js设置、获取单值cookie和多值cookie,代码如下:
1 var CookieUtil = (function () {
2 var Cookie = function () {
3 // 获取单值cookie
4 this.get = function(name) {
5 var start = document.cookie.indexOf(encodeURIComponent(name)) ;
6 var end = document.cookie.indexOf(';', start) ;
7 if(end == -1) {
8 end = document.cookie.length;
9 }
10 return decodeURIComponent(document.cookie.substring(start+name.length+1,end));
11 };
12
13 // 设置单值cookie
14 this.set = function(name, value, expires, path, domain, secure) {
15 var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
16 // 设置默认过期时间为七天
17 if(expires == undefined) {
18 var date = new Date();
19 date.setTime(date.getTime() + 7*24*60*60*1000);
20 expires = date ;
21 }
22 if(expires instanceof Date) {
23 cookieText += "; expires=" + expires.toGMTString();
24 }
25 if(path != undefined) {
26 cookieText += "; path=" + path;
27 }
28 if(domain != undefined) {
29 cookieText += "; domain" + domain;
30 }
31 if(secure != undefined) {
32 cookieText += "; secure";
33 }
34 document.cookie = cookieText;
35 };
36
37 // 清除单值cookie
38 this.unset = function(name, path, domain, secure) {
39 this.set(name, '', new Date(0), path, domain, secure );
40 };
41
42 // 设置多值cookie
43 this.setAll = function(name, subCookies, expires, path, domain, secure) {
44 var cookieText = ";" + encodeURIComponent(name) + "=",
45 arr = new Array();
46 for(var attr in subCookies) {
47 arr.push([encodeURIComponent(attr)] + ":" + encodeURIComponent(subCookies[attr]));
48 }
49 this.set(name, arr.join('&'), expires, path, domain, secure);
50 };
51
52 // 获取多值cookie
53 this.getAll = function(name) {
54 var obj = {};
55 var arr = this.get(name).split('&');
56 for(var i = 0, len = arr.length; i < len; i++) {
57 var tmpArr = arr[i].split(':');
58 obj[decodeURIComponent(tmpArr[0])] = decodeURIComponent(tmpArr[1]);
59 }
60 return obj;
61 };
62
63 // 获取多值cookie的子cookie
64 this.getSub = function(name, subname) {
65 var obj = this.getAll(name);
66 return obj[subname];
67 };
68
69 // 清除指定的多值cookie
70 this.unsetAll = function(name,path,domain,secure) {
71 this.unset(name, '', new Date(0), path, domain, secure);
72 };
73
74 // 清除指定多值cookie的子cookie
75 this.unsetSub = function(name, subname,path, domain, secure) {
76 var obj = this.getAll(name);
77 delete obj[subname];
78 this.setAll(name, obj, null, path, domain, secure);
79 };
80 };
81 return new Cookie();
82 })();