cookie-util

自己写的一个cookie-util,支持json

 1 (function (name, factory) {
 2     if (typeof define === 'function') {
 3         define(factory);
 4     } else if (typeof module !== 'undefined' && module.exports) {
 5         module.exports = factory();
 6     } else {
 7         this[name] = factory(this[name]);
 8     }
 9 })('cookie', function (originalCookie) {
10     11     
12     function cookie(name, value, options) {
13         var argLen = arguments.length;
14         if (argLen === 0) {
15             return all();
16         } else if (argLen === 1) {
17             return get(name);
18         } else {
19             return set(name, value, options);
20         }
21     }
22     cookie.originalCookie = originalCookie;
23     function all() {
24         var str = document.cookie,
25             res = {},
26             pairs, pair, name, value, i, len;
27         if (str === '') {
28             return res;
29         }
30         pairs = str.split(/;\s/g);
31         for (i = 0, len = pairs.length; i < len; i++) {
32             pair = pairs[i].split('=');
33             name = decodeURIComponent(pair[0]);
34             value = decodeURIComponent(pair[1]);
35             try {
36                 value = JSON.parse(value);
37             } catch(e) {
38                 
39             }
40             res[name] = value;
41         }
42         return res;
43     }
44 
45     function get(name) {
46         return all()[name];
47     }
48 
49     function set(name, value, settings) {
50         var str, d,
51             options = settings || {};
52         if(value === null) {
53             options.maxAge = 0;
54             options.expires = -1;
55         }
56         if(value && typeof value === 'object') {
57             value = JSON.stringify(value);
58         }
59         str = encodeURIComponent(name) + '=' + encodeURIComponent(value);
60         if(options.maxAge != null) {
61             str += '; max-age=' + options.maxAge;
62         }
63         if(options.expires != null) {
64             d = new Date();
65             d.setTime(d.getTime() + options.expires * 1000);
66             str += '; expires=' + d.toUTCString();
67         }
68         if(options.path) {
69             str += '; path=' + options.path;
70         }
71         if(options.domain) {
72             str += '; domain=' + options.domain;
73         }
74         if(options.secure) {
75             str += '; secure';
76         }
77         document.cookie = str;
78     }
79 
80     return cookie;
81 });

 

posted @ 2016-01-25 09:33  coIorZ  阅读(190)  评论(0编辑  收藏  举报