DIV CSS 佈局教程網

jQuery Cookie 操作插件用法與原始碼解析
編輯:JQuery特效代碼     

基本用法四則

// 設定 cookie
$.cookie('name', 'value');

// 建立含有效期、路徑、網域、安全性等選項的 cookie
$.cookie('name', 'value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });

// 刪除 cookie:把值設為 null 即可
$.cookie('name', null);

// 讀取 cookie
var account = $.cookie('name');

插件原始碼

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {          // 有傳值 → 設定
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;               // 負的過期時間 = 立即失效
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            // 使用 expires 屬性,max-age 在 IE 上不受支援
            expires = '; expires=' + date.toUTCString();
        }
        var path   = options.path   ? '; path='   + options.path   : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value),
                           expires, path, domain, secure].join('');
    } else {                                    // 只傳名稱 → 讀取
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // 判斷這段是否以我們要的名稱開頭
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

與 Discuz! 的實作對照

順手看了下 Discuz! 的 cookie 處理,發現它少了一段「以分號分割後逐項比對」的邏輯:

function getcookie(name) {
    var cookie_start = document.cookie.indexOf(name);
    var cookie_end = document.cookie.indexOf(";", cookie_start);
    return cookie_start == -1 ? '' : unescape(document.cookie.substring(
        cookie_start + name.length + 1,
        (cookie_end > cookie_start ? cookie_end : document.cookie.length)));
}

function setcookie(cookieName, cookieValue, seconds, path, domain, secure) {
    var expires = new Date();
    expires.setTime(expires.getTime() + seconds);
    document.cookie = escape(cookieName) + '=' + escape(cookieValue)
        + (expires ? '; expires=' + expires.toGMTString() : '')
        + (path ? '; path=' + path : '/')
        + (domain ? '; domain=' + domain : '')
        + (secure ? '; secure' : '');
}

兩種實作的取捨

Discuz! 版本用 indexOf(name) 直接搜尋,速度稍快,但有個隱憂:若要找 uid,而 cookie 裡同時存在 myuid,就可能誤命中。jQuery 插件版本先 split 再逐項前綴比對,雖然多一層迴圈,卻不會有這種前綴碰撞的問題。

另一個實務提醒:cookie 有 4KB 上限且以明文傳輸,不要拿來存放敏感資料;同時在設定時明確給 path,否則子路徑頁面可能讀不到上層設定的值。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved