• js操作cookie的一些注意项


    

           这两天做购物车逻辑。依照通常的做法,把预购信息存放在cookie里,结果发生了非常多不可理喻的事情,完整的证明了我对cookie的无知。

    尴尬

           这么多年。非常少用cookie,由于认为它不安全。但有些情况使用cookie会大大简化逻辑和系统负担,比方登录验证和购物车,仅仅要设计和处理得好,也不会有安全问题。

           正是由于用的少。偶尔用到,也仅仅是接触到皮毛,因此,对cookie的理解和掌握就很有限,一些无知的地方,这次就暴露无遗了。。

    。。

           以下把遇到问题总结一下,给大家一些參考吧,不一定是对的。都是自己測试得来的经验。

           1. cookie假设指定过期时间为0,也就是永只是期,就不能被删除。

                   因此想要改动和删除cookie,最初创建时,过期时间必须给个确定值,不要给0值。

                   这是一号坑,文档里不说明一下,害死人了。

    。。

           2. cookie不仅有过期时间的控制。还能够控制作用域、作用页面路径。

                   但出于安全考虑。作用域不能用js操作,必须在服务端操作。

                   这是二号坑。。

    。。给了參数,却不能用,又不说明,很害人。。。。

                   而作用页面的路劲能够用js指定。

          3. 删除cookie时注意,创建时带路径时,删除时也要带上,不然删除不了。


            以下是网上找到的jquery.cookie.js的源代码:

    (function (factory) {
        if (typeof define === 'function' && define.amd) {
            define(['jquery'], factory);
        } else if (typeof exports === 'object') {
            module.exports = factory(require('jquery'));
        } else {
            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) { s = s.slice(1, -1).replace(/\"/g, '"').replace(/\\/g, '\'); } try { 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) { if (arguments.length > 1 && !$.isFunction(value)) { options = $.extend({}, config.defaults, options); if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setMilliseconds(t.getMilliseconds() + days * 864e+5); } return (document.cookie = [ encode(key), '=', stringifyCookieValue(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', options.path ?

    '; path=' + options.path : '', options.domain ?

    '; domain=' + options.domain : '',//不要被这里迷惑,没实用的,假设真赋值了,仅仅会导致写入失败。 options.secure ?

    '; secure' : '' ].join('')); } var result = key ? undefined : {}, cookies = document.cookie ?

    document.cookie.split('; ') : [], i = 0, l = cookies.length; for (; i < l; i++) { var parts = cookies[i].split('='), name = decode(parts.shift()), cookie = parts.join('='); if (key === name) { result = read(cookie, value); break; } if (!key && (cookie = read(cookie)) !== undefined) { result[name] = cookie; } } return result; }; config.defaults = {}; $.removeCookie = function (key, options) { $.cookie(key, '', $.extend({}, options, { expires: -1 })); return !$.cookie(key); }; }));


    购物车使用方法举例:

    function GetSCart() {
        var sc = $.cookie("S_Cart");
        return sc ?

    JSON.parse($.cookie("S_Cart")) : null; } function GetSCartNum() { var dt = GetSCart(); if (dt && Object.prototype.toString.call(dt) === '[object Array]' && dt.length > 0) { return dt.length; } else { return 0; } } function addSCart(id, num) { if (!id) return; num = num || 1; var dt = GetSCart(); if(dt){ var isExist = false; if (Object.prototype.toString.call(dt) === '[object Array]' && dt.length > 0) { for (var i in dt) { if (dt[i].id == id) { dt[i].num = num; isExist = true; } } if (!isExist) { clearSCart(); dt.push({ "id": id, "num": num }); } } else { dt = [{ "id": id, "num": num }]; } } else { dt = [{ "id": id, "num": num }]; } $.cookie("S_Cart", JSON.stringify(dt), { expires: 10, path: '/' }); return dt; } function delSCart(id) { if (!id) return; var dt = GetSCart(); if (dt) { if (Object.prototype.toString.call(dt) === '[object Array]' && dt.length > 0) { var idx = -1; for (var i in dt) { idx = dt[i].id == id ?

    i : -1; } if (idx > -1) { dt.splice(i, 1); clearSCart(); $.cookie("S_Cart", JSON.stringify(dt), { expires: 10, path: '/' }); } } } } function clearSCart() { $.cookie("S_Cart", null, { path: '/' }); }


    这是c#后台取cookie的方法:

                var ck = Request.Cookies["S_Cart"];
                var sCart = HttpUtility.UrlDecode(ck == null ?

    "" : ck.Value);

    c#转json串为对象的方法:

                if (!string.IsNullOrWhiteSpace(S_Cart))
                {
                    List<S_CartParam> cs = new List<S_CartParam>();
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(cs.GetType());
                    MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(S_Cart));
                    cs = serializer.ReadObject(mStream) as List<S_CartParam>;
                }



    
    



    
  • 相关阅读:
    javascript base64 encode decode 支持中文
    php laravel v5.1 消息队列
    Linux C语言 取得MTU (最大传输单元)
    javascript 字符串 数字反转 字母大小写互换
    为Python安装Redis库
    php 日期相关的类 DateInterval DateTimeZone DatePeriod
    php安全 过滤、验证、转义
    python学习笔记之---多种方式实现list去重
    Python函数重载机制?
    说说下面几个概念:同步,异步,阻塞,非阻塞?
  • 原文地址:https://www.cnblogs.com/slgkaifa/p/7291558.html
Copyright © 2020-2023  润新知