「最近看過」是電商網站的標準配備。本文記錄一個以 Cookie 為儲存媒介的實作:使用者每次進入商品頁就把資訊寫入 Cookie,列表區塊則定時讀取並渲染。
整個實作需要兩個檔案:history.js 負責記錄的存取與渲染,json.js 負責 JSON 的序列化與反序列化。
// 新增一筆瀏覽記錄
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 "";
}
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 尚未普及的年代,因此自己實作了序列化。以今天的標準來看,有幾個地方值得改善:
整體流程(寫入 → 讀取 → 解析 → 渲染)的設計思路仍然通用,只要把儲存層換成 localStorage,程式碼會短很多也更可靠。