/*!
 * jQuery Cookie Plugin v1.4.0
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2013 Klaus Hartl
 * Released under the MIT license
 * Usage
 
Create session cookie:

$.cookie('the_cookie', 'the_value');
Create expiring cookie, 7 days from then:

$.cookie('the_cookie', 'the_value', { expires: 7 });
Create expiring cookie, valid across entire site:

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

$.cookie('the_cookie'); // => "the_value"
$.cookie('not_existing'); // => undefined
Read all available cookies:

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

// Returns true when cookie was found, false when no cookie was found...
$.removeCookie('the_cookie');

// Same path as when the cookie was written...
$.removeCookie('the_cookie', { path: '/' });
 */
(function(factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as anonymous module.
        define(['jquery'], factory);
    } 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.
            s = decodeURIComponent(s.replace(pluses, ' '));
        } catch (e) {
            return;
        }

try {
            // If we can't parse the cookie, ignore it, it's unusable.
            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.setDate(t.getDate() + days);
            }

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) {
            // Must not alter options, thus extending a fresh object...
            $.cookie(key, '', $.extend({}, options, {
                expires: -1
            }));
            return true;
        }
        return false;
    };

}));

另外,目前javascript使用非常多的json格式,如果希望存储在本地,可以直接调用JSON.stringify()将其转为字符串。读取出来后调用JSON.parse()将字符串转为json格式,如下所示:

var obj = {
           "12345":{
               "id":"45",
               "name":"pp"
           }
       }
$.cookie("test",JSON.stringify(obj));
console.log(JSON.parse($.cookie("test")))

js cookie存储方法的更多相关文章

  1. js cookie使用方法详解

    代码如下 复制代码 <script>function getCookie(c_name){ if (document.cookie.length>0){ //先查询cookie是否为 ...

  2. js读写Cookie问题(Cookie存储时长、Cookie存储域)汇总

    在采集网站用户行为数据/使用js对用户行为做交互时,经常会使用到Cookie,了解Js Cookie的读写,以及一些细节,非常重要.   什么是Cookie 所谓Cookie,只是一条极为短小的信息, ...

  3. [转]javascript js cookie的存储,获取和删除

    本文转自:http://www.jb51.net/article/13240.htm 使用方法: //1.存储Cookie //2.参数说明: 1.参数1:Cookie存储Name,参数2:Cooki ...

  4. Flask 框架中 上下文基础理念,包括cookie,session存储方法,requset属性,current_app模块和g模块

    Flask中上下文,分为请求上下文和应用上下文.既状态留存 ,就是把变量存在某一个地方可以调用 请求上下文:实际就是request和session用法理念,既都是可以存储东西. 应用上下文:既变量共享 ...

  5. JS访问或设置cookie的方法+跨域调用方法

    无意中从163网站获取的JS访问或设置cookie的方法,Log到日志上以防遗忘 //COOKIE功能检查function fCheckCookie(){    if(!navigator.cooki ...

  6. 前端Js跨域方法汇总—剪不断,理还乱,是跨域

    1.通过jsonp跨域2.通过修改document.domain来跨子域(iframe)3.隐藏的iframe+window.name跨域4.iframe+跨文档消息传递(XDM)5.跨域资源共享 C ...

  7. jquery.cookie使用方法

    jquery.cookie 使用方法 一个轻量级的 cookie 插件,可以读取.写入.删除 cookie . jquery.cookie.js 的配置 首先包含 jQuery 的库文件,在后面包含 ...

  8. JS cookie的使用

    js设置cookie有很多种方法. 第一种:(这个是w3c官网的代码) <script> //设置cookie function setCookie(cname, cvalue, exda ...

  9. c#.net与vb.net中读写Cookie的方法!

    Cookie (HttpCookie的实例)提供了一种在 Web 应用程序中存储用户特定信息的方法.例如,当用户访问您的站点时,您可以使用 Cookie 存储用户首选项或其他信息.当该用户再次访问您的 ...

随机推荐

  1. HTML5-链接

    链接:外部,图片,内部 <!DOCTYPE html> <html> <head lang="en"> <meta charset=&qu ...

  2. Python学习笔记1——Python基础

    一. 数据类型和变量 整数:十六进制用0x前缀和0-9,a-f表示 浮点数:小数,科学计数法:10用e代替:整数和浮点数在计算机内部存储的方式是不同的,整数运算永远是精确的(包括除法),浮点数运算则可 ...

  3. FFmpeg 2.1 发布

    FFmpeg是一套可以用来记录.转换数字音频.视频,并能将其转化为流的开源计算机程序.它包括了目前领先的音/视频编码库 libavcodec. FFmpeg是在Linux下开发出来的,但它可以在包括W ...

  4. TFS 改服务器IP 域名 端口方法

    长春电信伴随着开始的严打,所有未备案的80,8080等常用web端口都被封,使得原用8080作为服务端口的tfs代码服务器无法使用,现提供方法如下: 1.关掉VS 2.去掉要改的解决方案的sln文件的 ...

  5. nginx(3、负载均衡)

    当业务系统需要配置集群时,会用到nginx的负载均衡功能.nginx提供如下几种: 1.轮询(默认):将不同的请求随机分配给配置的服务器,若出现宕机,则自动切换:轮询可配置weight值,即权重,权重 ...

  6. UWP开发笔记——嵌套式页面的实现

    绪论 UWP开发中,Page是最常用的Control之一,通常情况下,在开发的application中,每一个页面就是一个Page.有时候,为了开发整合度更高,UI表现更为一致的UI,开发者需要把UI ...

  7. ReentrantLock实现原理深入探究

    前言 这篇文章被归到Java基础分类中,其实真的一点都不基础.网上写ReentrantLock的使用.ReentrantLock和synchronized的区别的文章很多,研究ReentrantLoc ...

  8. JavaScript使用DeviceOne开发实战(四)仿优酷视频应用

    开发之前需要考虑系统的差异性,比如ios手机没有回退键,所以在开发时一定要考虑二级界面需要有回退键,否则ios的手机就会陷入到这个页面出不去了.安卓系统有回退键,针对这个情况需要要求用户在3秒钟之内连 ...

  9. Wix 安装部署(一)同MSBuild 自动生成打包文件

    因为项目需要,最近在研究Wix打包部署,园子里也有一些关于wix的博客,方方面面,讲的点各不同.我自己也在测试过程中,写下过程,以供参考.最新版本WiX Toolset v3.7,如何安装的就不说了, ...

  10. Java提高配(三七)-----Java集合细节(三):subList的缺陷

    我们经常使用subString方法来对String对象进行分割处理,同时我们也可以使用subList.subMap.subSet来对List.Map.Set进行分割处理,但是这个分割存在某些瑕疵. 一 ...