DIV CSS 佈局教程網

用 Cookie 實作瀏覽歷史:中文 escape 編碼與自建 JSON 序列化
編輯:關於JavaScript     

「最近看過」是電商常見功能。由於不需要伺服器紀錄訪客身分,用 Cookie 存放一份 JSON 是最輕量的做法。但中文存進 Cookie 會遇到編碼問題,本文完整示範。

一、資料結構設計

每筆紀錄包含這些欄位:

pro_id     : 產品 id
brand_name : 品牌
pro_name   : 產品名稱
price      : 價格
catalog    : 機型
img        : 圖片路徑
file_name  : 檔名(用來組出詳情頁網址)

二、新增一筆瀏覽紀錄

var addHistory = function(pro_id, brand_name, pro_name, price, catalog, img, file_name) {
    var stringCookie = getCookie('history');
    var stringHistory = ("" != stringCookie) ? stringCookie : "{history:[]}";
    var json = new JSON(stringHistory);

    // 把現有 id 串成字串,用來判斷是否已看過
    var pro_ids = '';
    jQuery.each(json['history'], function(i, val) {
        pro_ids += json['history'][i].pro_id + ",";
    });

    if (jQuery.trim(pro_id) == '' || pro_ids.indexOf(pro_id) == -1) {
        var e = "{pro_id:" + pro_id
              + ",brand_name:'" + brand_name + "'"
              + ",pro_name:'"   + pro_name   + "'"
              + ",price:'"      + price      + "'"
              + ",catalog:'"    + catalog    + "'"
              + ",img:'"        + img        + "'"
              + ",file_name:'"  + file_name  + "'}";

        json['history'].push(e);           // 加入新紀錄
        setCookie('history', json.toString(), 30);
    }
}

用 indexOf 去重,同一個產品不會重複出現在列表中。

三、Cookie 的讀寫

// 設定 cookie,30 天後過期
var setCookie = function(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    var cookieVal = c_name + "=" + escape(value)
                  + ((expiredays == null) ? ""
                  : ";path=/;expires=" + exdate.toGMTString());
    document.cookie = cookieVal;
}

// 讀取 cookie
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        var c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            var c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

// 清空瀏覽歷史
function DeleteCookie() {
    setCookie('history', "{history:[]}", 30);
}

escape 與 unescape 成對使用,把中文與特殊字元轉成 %uXXXX 形式,避免 Cookie 值被 ;、, 等分隔字元破壞。

四、渲染歷史列表

var DisplayHistory = function() {
    var p_ele = document.getElementById('history');
    while (p_ele.firstChild) {
        p_ele.removeChild(p_ele.firstChild);      // 先清空
    }

    var historyJSON = getCookie('history');
    var json = new JSON(historyJSON);
    var displayNum = 6;                            // 最多顯示 6 筆

    for (var i = json['history'].length - 1; i >= 0; i--) {
        addLi(json['history'][i]['pro_id'],
              json['history'][i]['brand_name'],
              json['history'][i]['pro_name'],
              json['history'][i]['price'],
              json['history'][i]['catalog'],
              json['history'][i]['img'],
              json['history'][i]['file_name'], "history");
        displayNum--;
        if (displayNum == 0) break;
    }
}

var addLi = function(pro_id, brand_name, pro_name, price, catalog, img, file_name, pid) {
    var a = document.createElement('a');
    a.setAttribute('href', '/proDetail/' + file_name);
    a.setAttribute("target", "_blank");
    jQuery(a).html(
        "<img src='" + unescape(img) + "' onerror=\"this.src='/images/nopic.gif'\"
         width='90' height='50' />"
        + "<h3>" + unescape(brand_name + pro_name + catalog) + "</h3>"
        + "<span class='price'>" + unescape(price) + "</span>"
    );
    var li = document.createElement('li');
    li.appendChild(a);
    jQuery(li).appendTo("#" + pid);
}

五、自建的 JSON 類

範例中為了避免依賴外部程式庫,自己實作了一個極簡的 JSON 序列化:

var JSON = function(sJSON) {
    this.objType = (typeof sJSON);
    if (this.objType == 'string' && '' == sJSON) {
        sJSON = '{history:[]}';
    }
    this.self = [];
    (function(s, o) {
        for (var i in o) {
            o.hasOwnProperty(i) && (s[i] = o[i], s.self[i] = o[i]);
        }
    })(this, (this.objType == 'string') ? eval('0,' + sJSON) : sJSON);
}

JSON.prototype = {
    toString: function() { return this.getString(); },
    valueOf:  function() { return this.getString(); },
    getString: function() { /* 遞迴拼出 JSON 字串 */ },
    push: function(sName, sValue) {
        this.self[sName] = sValue;
        this[sName] = sValue;
    }
}

六、呼叫方式

addHistory("<%=uuid%>",
           escape("<%=factoryname%>"),
           escape("<%=name%>"),
           escape("<%=price%>"),
           escape("<%=catalogname%>"),
           escape("<%=img%>"),
           escape("<%=file_name%>"));

七、這份程式碼今天必須修正的地方

上述寫法反映了 2010 年前後的技術環境,直接沿用會有幾個實際風險:

  1. escape/unescape 已廢棄:不支援 Unicode 且不適用於 URI。請改用 encodeURIComponent/decodeURIComponent。
  2. 自建 JSON 類毫無必要:所有瀏覽器都原生支援 JSON.parse 與 JSON.stringify,而且更快更安全。原寫法中的 eval 更是明確的程式碼注入風險。
  3. 用 innerHTML 拼接字串會有 XSS 風險:產品名稱若含 <img onerror=...> 就會被執行。應改用 textContent。
  4. Cookie 容量只有 4KB:每筆紀錄含七個欄位,大約只能存十幾筆就會超限而靜默失敗。這種情境更適合 localStorage(通常 5MB)。
  5. Cookie 中缺少 SameSite 與 Secure 設定:雖然這裡只是瀏覽紀錄,養成習慣仍應補上。

八、現代等效寫法

var HISTORY_KEY = "history";
var MAX_ITEMS = 20;

function getHistory() {
    try {
        return JSON.parse(localStorage.getItem(HISTORY_KEY)) || [];
    } catch (e) {
        return [];   // 資料損毀時降級處理,不要讓整個功能掛掉
    }
}

function addHistory(item) {
    var list = getHistory().filter(function (x) { return x.pro_id !== item.pro_id; });
    list.unshift(item);                       // 新的放最前面
    if (list.length > MAX_ITEMS) list.length = MAX_ITEMS;
    localStorage.setItem(HISTORY_KEY, JSON.stringify(list));
}

function renderHistory(container) {
    container.textContent = "";               // 清空
    getHistory().slice(0, 6).forEach(function (item) {
        var li  = document.createElement("li");
        var a   = document.createElement("a");
        a.href  = "/proDetail/" + item.file_name;

        var img = document.createElement("img");
        img.src = item.img;
        img.alt = item.pro_name;
        img.width = 90; img.height = 50;
        img.onerror = function () { this.src = "/images/nopic.gif"; };

        var h3 = document.createElement("h3");
        h3.textContent = item.brand_name + item.pro_name + item.catalog;   // 安全

        var price = document.createElement("span");
        price.className = "price";
        price.textContent = item.price;

        a.appendChild(img); a.appendChild(h3); a.appendChild(price);
        li.appendChild(a);
        container.appendChild(li);
    });
}

全程使用 DOM API 建立節點、以 textContent 填入文字,既不必處理編碼,也不存在注入風險,程式碼還比原版短。

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