jq cookie 插件使用 增删改查以及拓展之管理用户登录状态

jQuery Cookie官网地址:http://plugins.jquery.com/cookie/jQuery
由于jQuery.Cookie依赖jQuery,使用之前需要先引入jQuery,然后再引用jQuery.Cookie
该插件也可以作为AMD或CommonJS模块加载。
 <!-- 一般放尾部 -->
<script type="text/javascript" src="js/jquery-1.12.0.min.js"></script>
<script type="text/javascript" src="js/jquery.cookie.js"></script>

实例:

创建Cookie

创建一个临时cookie,随浏览器关闭消失:

$.cookie('the_cookie', 'the_value');

创建一个有效时间七天的cookie:

$.cookie('the_cookie', 'the_value', { expires: 7 });

创建一个有效期七天,有效路径为根目录的cookie:

$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });

读取Cookie:

$.cookie('the_cookie'); // => "the_value"
$.cookie('not_existing'); // => undefined

读取所有Cookie:

$.cookie(); // => { "the_cookie": "the_value", "...remaining": "cookies" }

删除Cookie:

// 存在返回true并删除,不存在返回false...
$.removeCookie('the_cookie');

// 删除指定路径下的所有cookie...
$.removeCookie('the_cookie', { path: '/' });

注意:删除cookie时,除非您依赖默认选项,否则必须传递用于设置cookie的完全相同的路径,域和安全选项。

配置

raw

默认情况下,cookie 读写编码的 encoded/decoded 是使用encodeURIComponent/decodeURIComponent 。将raw设置为true不进行编码:

$.cookie.raw = true;

json

使用 JSON.stringify and JSON.parse对json对象进行编码:

$.cookie.json = true;

Cookie选项

Cookie属性可以通过设置$.cookie.defaults对象的属性或$.cookie(),将一个普通对象传递给options参数来单独调用来覆盖默认选项。

有效期

expires: 365

定义cookie的生命周期。值可以是一个NumberDate对象,Number的值将被解释为创建时间起的天数。如果省略,则Cookie变成会话cookie。

路径

path: '/'

定义cookie有效的路径。默认情况下,Cookie的路径是创建cookie的页面的路径(标准浏览器行为)。如果你想让它可用于整个域的使用path: '/‘。默认值:创建cookie的页面路径。

有关Internet Explorer的注意事项:

由于底层WinINET InternetGetCookie实现中的一个隐含的错误,IE的document.cookie如果设置了包含文件名的路径属性,则不会返回cookie。

这意味着在路径:path: window.location.pathname包含像这样的文件名:/check.html,则不能设置路径(或者,至少这里的cookie不能被正确读取)。

domain: 'example.com'

定义cookie有效的域。默认:创建cookie的页面的域。

安全

secure: true

如果为true,则Cookie传输需要安全协议(https)。默认:false

转换器

提供一个转换函数作为可选的最后一个参数来读取,以便将cookie的值更改为不同的表示。

将值解析为数字的示例:

$ .cookie('foo''42'); 
$ .cookie('foo'Number); // => 42

处理使用escape(第三方Cookie)编码的cookie:

$ .cookie.raw = TRUE; 
$ .cookie('foo',unescape);

您可以传递任意的转换函数。

翻译自Github。
jQuery.cookie. readme

附上源码:

/*!
 * jQuery Cookie Plugin v1.4.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2013 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // CommonJS
        factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

    var pluses = /\+/g;

    function encode(s) {
        return config.raw ? s : encodeURIComponent(s);
    }

    function decode(s) {
        return config.raw ? s : decodeURIComponent(s);
    }

    function stringifyCookieValue(value) {
        return encode(config.json ? JSON.stringify(value) : String(value));
    }

    function parseCookieValue(s) {
        if (s.indexOf('"') === 0) {
            // This is a quoted cookie as according to RFC2068, unescape...
            s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
        }

        try {
            // Replace server-side written pluses with spaces.
            // If we can't decode the cookie, ignore it, it's unusable.
            // If we can't parse the cookie, ignore it, it's unusable.
            s = decodeURIComponent(s.replace(pluses, ' '));
            return config.json ? JSON.parse(s) : s;
        } catch(e) {}
    }

    function read(s, converter) {
        var value = config.raw ? s : parseCookieValue(s);
        return $.isFunction(converter) ? converter(value) : value;
    }

    var config = $.cookie = function (key, value, options) {

        // Write

        if (value !== undefined && !$.isFunction(value)) {
            options = $.extend({}, config.defaults, options);

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

            return (document.cookie = [
                encode(key), '=', stringifyCookieValue(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path    ? '; path=' + options.path : '',
                options.domain  ? '; domain=' + options.domain : '',
                options.secure  ? '; secure' : ''
            ].join(''));
        }

        // Read

        var result = key ? undefined : {};

        // To prevent the for loop in the first place assign an empty array
        // in case there are no cookies at all. Also prevents odd result when
        // calling $.cookie().
        var cookies = document.cookie ? document.cookie.split('; ') : [];

        for (var i = 0, l = cookies.length; i < l; i++) {
            var parts = cookies[i].split('=');
            var name = decode(parts.shift());
            var cookie = parts.join('=');

            if (key && key === name) {
                // If second argument (value) is a function it's a converter...
                result = read(cookie, value);
                break;
            }

            // Prevent storing a cookie that we couldn't decode.
            if (!key && (cookie = read(cookie)) !== undefined) {
                result[name] = cookie;
            }
        }

        return result;
    };

    config.defaults = {};

    $.removeCookie = function (key, options) {
        if ($.cookie(key) === undefined) {
            return false;
        }

        // Must not alter options, thus extending a fresh object...
        $.cookie(key, '', $.extend({}, options, { expires: -1 }));
        return !$.cookie(key);
    };

}));
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值