DIV CSS 佈局教程網

jQuery 基於 json 與 cookie 實現購物車的方法
編輯:關於JavaScript     

購物車是電商網站的核心功能之一。本文示範如何用 jQuery 搭配 json 與 cookie,把購物車的商品數據保存在瀏覽器本地,實現添加商品並累加數量的效果。

json 格式如下:

[{'ProductID':ABC','Num':'1'},{'ProductID':DEF,'Num':'2'}]

這裡使用到了 $.cookie 這個插件(插件代碼附於文末)。添加商品的核心函數如下:

/* 添加商品及數量到購物車cookie中,返回當前商品在cookie中的總數 */
function AddToShoppingCar(id, num) {
    var _num = 1;
    if (num != undefined) _num = num;
    var totalNum = _num; //總數默認為傳入參數
    var cookieSet = { expires: 7, path: '/' }; //設置cookie路徑
    var jsonStr = "[{'ProductID':'" + id + "','Num':'" + _num + "'}]"; //構造json字符串
    if ($.cookie(cookieProductID) == null) {
        $.cookie(cookieProductID, jsonStr, cookieSet); //如果沒有這個cookie就設置他
    } else {
        var jsonObj = eval('(' + $.cookie(cookieProductID) + ')'); //把json字符串轉換成對象
        var findProduct = false;//是否找到產品ID
        for (var obj in jsonObj) {
            if (jsonObj[obj].ProductID == id) {
                jsonObj[obj].Num = Number(jsonObj[obj].Num) + _num;
                totalNum = jsonObj[obj].Num;
                findProduct = true;
                break;
            }
        }
        if (findProduct == false) { //沒找到,則添加
            jsonObj[jsonObj.length] = new Object();
            jsonObj[jsonObj.length - 1].ProductID = id;
            jsonObj[jsonObj.length - 1].Num = num;
        }
        $.cookie(cookieProductID, JSON.stringify(jsonObj), cookieSet); //寫入coockie
    }
    return totalNum;
}

以下為 cookie 插件代碼:

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

核心思路是:把購物車數據序列化為 json 字符串存入 cookie,添加商品時先讀取並解析現有數據,若已存在該商品則累加數量,否則追加新項,最後再寫回 cookie,从而在无后台的情况下实现本地购物车。

希望本文所述對大家 jQuery 程序設計有所幫助。

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