把 ECShop 系列的 transport.js 和 jQuery 放在同一頁,很容易出現莫名其妙的錯誤。追下去會發現根源在 transport.js 裡。
在 /js/transport.js 大約第 580 到 590 行之間,有這麼一段:
Object.prototype.toJSONString = function () { ************** }
它為了讓任何物件都能呼叫 toJSONString(),直接擴充了 Object.prototype。這等于替所有物件都掛上一個可列舉屬性,不只污染全域,也會讓 jQuery 在遍歷物件屬性時拿到意料之外的成員,於是就衝突了。
解法是這段程式碼必須停用,再用別的方式取代序列化功能。
把專案裡所有用到 *.toJSONString 的地方,改成呼叫自寫的 obj2str 函式。以 /js/common.js 第 29 行為例,原本是:
Ajax.call('flow.php?step=add_to_cart', 'goods=' + goods.toJSONString, addToCartResponse, 'POST', 'JSON');
改成:
Ajax.call('flow.php?step=add_to_cart', 'goods=' + obj2str(goods), addToCartResponse, 'POST', 'JSON');
obj2str 的實作如下:
function obj2str(o) {
var r = [];
if (typeof o == "string") return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
if (typeof o == "undefined") return "undefined";
if (typeof o == "object") {
if (o === null) return "null";
else if (!o.sort) {
for (var i in o) r.push("\"" + i + "\"" + ":" + obj2str(o[i]));
r = "{" + r.join() + "}";
} else {
for (var i = 0; i < o.length; i++) r.push(obj2str(o[i]));
r = "[" + r.join() + "]";
}
return r;
}
return o.toString();
}
/*
Object.prototype.toJSONString = function () {
……
// Join all of the fragments together and return.
a.push('}');
return a.join('');
};
*/
大致上這樣就能解決。不同專案可能還有零星的呼叫點要處理,這裡提供的是其中一種可行思路,不一定完全適用於你的網站,實際套用前建議先在自己的環境驗證一次。