DIV CSS 佈局教程網

用 Cookie 記錄瀏覽足跡:JS 打造商品瀏覽歷史的完整實作
編輯:關於JavaScript     

「最近看過」是電商網站的標準配備。本文記錄一個以 Cookie 為儲存媒介的實作:使用者每次進入商品頁就把資訊寫入 Cookie,列表區塊則定時讀取並渲染。

設計思路

  • 進入商品頁時,呼叫 JS 把商品資訊以 JSON 字串形式存進 Cookie。
  • 瀏覽記錄的顯示,是從 Cookie 讀出字串、解析成物件,再動態組出 HTML 元素。
  • 因為使用者可能同時開啟多個分頁,各頁的記錄需即時同步,所以每秒重新讀取一次。

整個實作需要兩個檔案:history.js 負責記錄的存取與渲染,json.js 負責 JSON 的序列化與反序列化。

history.js

// 新增一筆瀏覽記錄
var addHistory = function (num, id) {
  var stringCookie = getCookie('history');
  var stringHistory = "" != stringCookie ? stringCookie : "{history:[]}";
  var json = new JSON(stringHistory);
  var e = "{num:" + num + ",id:" + id + "}";
  json['history'].push(e);
  setCookie('history', json.toString(), 30);
};

// 渲染歷史記錄
var DisplayHistory = function () {
  var p_ele = document.getElementById('history');
  while (p_ele.firstChild) {
    p_ele.removeChild(p_ele.firstChild);
  }
  var json = new JSON(getCookie('history'));
  var displayNum = 6;
  for (i = json['history'].length - 1; i > 0; i--) {
    addLi(json['history'][i]['num'], json['history'][i]['id'], "history");
    displayNum--;
    if (displayNum == 0) break;
  }
};

// 組出一個 li 元素
var addLi = function (num, id, pid) {
  var a = document.createElement('a');
  a.setAttribute('href', 'product.action?pid=' + id);
  a.appendChild(document.createTextNode(num));
  var li = document.createElement('li');
  li.appendChild(a);
  document.getElementById(pid).appendChild(li);
};

// 寫入 Cookie
var setCookie = function (c_name, value, expiredays) {
  var exdate = new Date();
  exdate.setDate(exdate.getDate() + expiredays);
  var cookieVal = c_name + "=" + escape(value) +
    ((expiredays == null) ? "" : ";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 "";
}

json.js

var JSON = function (sJSON) {
  this.objType = (typeof sJSON);
  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 () {
    var sA = [];
    (function (o) {
      var oo = null;
      sA.push('{');
      for (var i in o) {
        if (o.hasOwnProperty(i) && i != 'prototype') {
          oo = o[i];
          if (oo instanceof Array) {
            sA.push(i + ':[');
            for (var b in oo) {
              if (oo.hasOwnProperty(b) && b != 'prototype') {
                sA.push(oo[b] + ',');
                if (typeof oo[b] == 'object') arguments.callee(oo[b]);
              }
            }
            sA.push('],');
            continue;
          } else {
            sA.push(i + ':' + oo + ',');
          }
          if (typeof oo == 'object') arguments.callee(oo);
        }
      }
      sA.push('},');
    })(this.self);
    return sA.slice(0).join('')
      .replace(/ objectobject ,/ig, '')
      .replace(/,\}/g, '}')
      .replace(/,\]/g, ']')
      .slice(0, -1);
  },
  push: function (sName, sValue) {
    this.self[sName] = sValue;
    this[sName] = sValue;
  }
};

實作檢討

這份程式碼寫於原生 JSON 尚未普及的年代,因此自己實作了序列化。以今天的標準來看,有幾個地方值得改善:

  • 直接用 JSON.stringify / JSON.parse:所有現代瀏覽器都支援,不必自己造輪子,也避開 eval 帶來的風險。
  • 注意 Cookie 容量:單個 Cookie 上限約 4KB,瀏覽記錄一多就會寫入失敗。實務上通常限制筆數,或改用 localStorage(上限約 5MB)。
  • 用 escape/unescape 並不安全:這組函式已被棄用,對非 ASCII 字元的處理也不完整,建議改用 encodeURIComponent。
  • 多分頁同步:用輪詢每秒讀取可行,但更省資源的作法是監聽 storage 事件,localStorage 變動時會自動通知其他分頁。

整體流程(寫入 → 讀取 → 解析 → 渲染)的設計思路仍然通用,只要把儲存層換成 localStorage,程式碼會短很多也更可靠。

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