萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery Cookie 插件完整使用手冊:讀寫刪除、過期、路徑、域、安全屬性與中文編碼

jQuery Cookie 是最經典的 Cookie 操作插件,API 簡潔、鏈式調用、自動編碼解碼。本文匯總所有配置選項、實戰代碼片段、中文亂碼解決、檢測 Cookie 可用性、完整調用模板。

1. 引用順序

<script src="jquery.min.js"></script>
<script src="jquery.cookie.js"></script>

2. 核心 API 速查

操作語法返回值
讀取$.cookie(name)字符串值 / null
寫入(會話級)$.cookie(name, value)undefined
寫入(持久化)$.cookie(name, value, {expires: 7})undefined
刪除$.cookie(name, null, options)undefined

3. 完整選項對象

$.cookie('name', 'value', {
    expires: 7,           // Number(天) | Date 對象
    path: '/',            // String,默認當前頁路徑
    domain: 'example.com',// String,默認當前域
    secure: true,         // Boolean,僅 HTTPS
    raw: false            // Boolean,true 關閉 encodeURIComponent
});

4. 實戰代碼片段

4.1 基礎讀寫刪除

// 寫入
$.cookie('theme', 'dark', { expires: 30, path: '/' });
// 讀取
var theme = $.cookie('theme'); // "dark" 或 null
// 刪除(需帶上寫入時的 path/domain)
$.cookie('theme', null, { path: '/', domain: 'example.com' });

4.2 會話級 vs 持久化

// 會話級:關閉瀏覽器失效
$.cookie('temp_flag', '1');

// 持久化:30 天
$.cookie('persist_flag', '1', { expires: 30, path: '/' });

4.3 中文編碼問題(核心優勢)

// 寫入中文
$.cookie('username', '張三'); // 內部自動 encodeURIComponent -> "%E5%BC%B5%E4%B8%89"
// 讀取自動解碼
var name = $.cookie('username'); // "張三"

// 若後端手動設置 Cookie 未編碼,導致讀取亂碼
// 解決:關閉插件自動編碼
$.cookie.raw = true; // 全局關閉
// 或單次關閉
$.cookie('raw_cookie', '已編碼值', { raw: true });

4.4 分鐘級過期(非整天)

var date = new Date();
date.setTime(date.getTime() + 30 * 60 * 1000); // 30 分鐘
$.cookie('short_live', 'data', { expires: date, path: '/' });

4.5 檢測瀏覽器 Cookie 是否啟用

function areCookiesEnabled() {
    var testKey = 'cookie_test_' + Date.now();
    var exp = new Date(Date.now() + 60000); // 1 分鐘
    document.cookie = testKey + '=1; expires=' + exp.toGMTString() + '; path=/';
    var enabled = document.cookie.indexOf(testKey + '=') !== -1;
    // 清理測試 Cookie
    document.cookie = testKey + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
    return enabled;
}

$(function () {
    if (!areCookiesEnabled()) {
        alert('請啟用 Cookie 以獲得完整功能');
    }
});

5. 完整調用模板(複製即用)

// 寫入完整配置
$.cookie('key', 'value', {
    expires: 30,           // 30 天
    path: '/',             // 全站
    domain: '.example.com',// 跨子域
    secure: true,          // 僅 HTTPS
    raw: false             // 自動編碼中文
});

// 刪除完整配置
$.cookie('key', null, {
    path: '/',
    domain: '.example.com'
});

6. 遷移建議:現代替代方案

  • localStorage / sessionStorage:5MB+ 存儲,不隨請求發送,同源策略,同步 API,適合非敏感數據、緩存。
  • IndexedDB:大量結構化數據、異步、支持索引查詢。
  • JWT (JSON Web Token):無狀態認證,攜帶在 Header,不依賴 Cookie。
  • HttpOnly Cookie + CSRF Token:傳統會話認證最佳組合。

jQuery Cookie 仍是維護舊專案、快速原型的利器;新專案優先考慮現代存儲方案。

copyright © 萬盛學電腦網 all rights reserved