JQuery /JS添加、刪除session


JQuery /JS添加、刪除session

這里需要引入JQuery還有操作session的js文件,JQuery在網上的CDN很多,可以自己找。例如:https://s3.pstatp.com/cdn/expire-1-M/jquery/3.3.1/jquery.min.js

接下來是操作session的JS引入,可以直接復制以下代碼,或者直接CDN引入http://yourjavascript.com/4294145691/jquerysession.js

    (function($){
    $.session = {
        _id: null,

        _cookieCache: undefined,


        _init: function()
        {
            this._id = 'sessionID';
            this._initCache();

			var matches = (new RegExp(this._generatePrefix() + "=([^;]+);")).exec(document.cookie);
            if (matches && document.location.protocol !== matches[1]) {
               this._clearSession();
               for (var key in this._cookieCache) {
                   try {
                       window.sessionStorage.setItem(key, this._cookieCache[key]);
                   } catch (e) {};
               }
            }

            document.cookie = this._generatePrefix() + "=" + document.location.protocol + ';path=/;expires=' + (new Date((new Date).getTime() + 28800000)).toUTCString(); // 加上八個小時=北京時間

        },

        _generatePrefix: function()
        {
            return '__session:' + this._id + ':';
        },

        _initCache: function()
        {
            var cookies = document.cookie.split(';');
            this._cookieCache = {};
            for (var i in cookies) {
                var kv = cookies[i].split('=');
                if ((new RegExp(this._generatePrefix() + '.+')).test(kv[0]) && kv[1]) {
                    this._cookieCache[kv[0].split(':', 3)[2]] = kv[1];
                }
            }
        },

        _setFallback: function(key, value, num)//參數分別是session的key、鍵值和過期時間,以天為單位,num=1即為1天,不傳或傳入非數字均默認為1天
        {
                  
                var cookie = this._generatePrefix() + key + "=" + value + ";path=/";
                if(!isNaN(num)){  
                    cookie += ";expires=" + (new Date(Date.now() +(86400000*Number(num)) )).toUTCString();            
               }else{
                console.log('!!!The third input value must be a number. Otherwise, it is set to 1 day by default.^_^');
                cookie += ";expires=" + (new Date(Date.now() +86400000 )).toUTCString();
               }
                document.cookie = cookie;
                this._cookieCache[key] = value;
                return this;
        },

        _getFallback: function(key)
        {
            if (!this._cookieCache) {
                this._initCache();
            }
            return this._cookieCache[key];
        },

        _clearFallback: function()
        {
            for (var i in this._cookieCache) {
                document.cookie = this._generatePrefix() + i + '=;path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
            }
            this._cookieCache = {};
        },

        _deleteFallback: function(key)
        {
            document.cookie = this._generatePrefix() + key + '=;path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT;'; // 把有效時間設置為過期
            delete this._cookieCache[key];
        },

        get: function(key)
        {
            return window.sessionStorage.getItem(key) || this._getFallback(key);
        },

        set: function(key, value, onceOnly)
        {
            try {
                window.sessionStorage.setItem(key, value);
            } catch (e) {}
            this._setFallback(key, value, onceOnly || false);
            return this;
        },
        
        'delete': function(key){
            return this.remove(key);
        },

        remove: function(key)
        {
            try {
            window.sessionStorage.removeItem(key);
            } catch (e) {};
            this._deleteFallback(key);
            return this;
        },

        _clearSession: function()
        {
          try {
                window.sessionStorage.clear();
            } catch (e) {
                for (var i in window.sessionStorage) {
                    window.sessionStorage.removeItem(i);
                }
            }
        },

        clear: function()
        {
            this._clearSession();
            this._clearFallback();
            return this;
        }

    };

    $.session._init();

})(jQuery);

引入后的使用方法:

設置添加、更改session並設置過期時間

$.session.set('key', 'value', 2);//參數分別是session的key、鍵值和過期時間,以天為單位,num=1即為1天,不傳或傳入非數字均默認為1天


獲取數據

$.session.get('key');


刪除數據

$.session.remove('key');


清空所有數據

$.session.clear();

轉載修改自:https://www.cnblogs.com/shouke/p/11324146.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM