1. 程式人生 > >js操作cookie的一些註意項

js操作cookie的一些註意項

時也 初創 string 過期 move exp 安全 完整 file



這兩天做購物車邏輯。依照通常的做法,把預購信息存放在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>;
            }










js操作cookie的一些註意項