码迷,mamicode.com
首页 > 其他好文 > 详细

cookie-util

时间:2016-01-25 09:52:59      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

自己写的一个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     cookie.orginalCookie = originalCookie;
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 
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 });

 

cookie-util

标签:

原文地址:http://www.cnblogs.com/coiorz/p/5156597.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!