1. 程式人生 > >jQuery基於json與cookie實現購物車的方法

jQuery基於json與cookie實現購物車的方法

構造 exp als com else cookies 一個 可選參數 int

/**
     * 添加商品及數量到購物車cookie中,返回當前商品在cookie中的總數
     */
    function AddToShoppingCar(id, num, type) {
        var _num = 1;
        if (num != undefined){
            _num = num;
        }
        if (type == undefined){
            alert("請設置產品種類");
            return false;
        }
        var totalNum = _num; //
總數默認為傳入參數 var cookieSet = { expires: 7, path: ‘/‘ }; //設置cookie路徑的 // $.cookie(cookieProductID, null, cookieSet);//清除Cookie // var jsonStr = "[{‘ProductID‘:‘" + id + "‘,‘Num‘:‘" + _num + "‘}]"; //構造json字符串,id是商品id num是這個商品的數量 var jsonStr = "[{‘ProductID‘:‘" + id + "‘,‘Num‘:‘" + _num + "‘,‘Type‘:‘" + type + "‘}]"; //
構造json字符串,id是商品id num是這個商品的數量 console.log(jsonStr); console.log($.cookie(cookieProductID)); if ($.cookie(cookieProductID) == null) { $.cookie(cookieProductID, jsonStr, cookieSet); //如果沒有這個cookie就設置他 // ============ var jsonObj = eval(‘(‘ + $.cookie(cookieProductID) + ‘)‘); //
如果有,把json字符串轉換成對象 var findProduct = false;//是否找到產品ID,找到則為TRUE,否則為FALSH for(var obj in jsonObj) { if(jsonObj[obj].ProductID == id) { console.log("數量:" + parseInt(jsonObj[obj].Num)); jsonObj[obj].Num = parseInt(jsonObj[obj].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; jsonObj[jsonObj.length - 1].Type = type; } $.cookie(cookieProductID, JSON.stringify(jsonObj), cookieSet); //寫入coockie JSON需要json2.js支持 // ============ }else{ var jsonObj = eval("(" + $.cookie(cookieProductID) + ")"); //如果有,把json字符串轉換成對象 var findProduct = false;//是否找到產品ID,找到則為TRUE,否則為FALSH for(var obj in jsonObj) { if(jsonObj[obj].ProductID == id) { console.log("數量:" + parseInt(jsonObj[obj].Num)); jsonObj[obj].Num = parseInt(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; jsonObj[jsonObj.length - 1].Type = type; } $.cookie(cookieProductID, JSON.stringify(jsonObj), cookieSet); //寫入coockie JSON需要json2.js支持 } return totalNum; // alert($.cookie(cookieProductID)); }

這裏使用到了 $.cookie這個插件。這個插件的代碼如下:

 /**
 *創建與給定的名稱和值和其他可選參數的cookie。
 *
 * @example $ .cookie(‘the_cookie‘,‘the_value‘);
 * @desc    設置cookie的值。
 * @example $ .cookie(‘the_cookie‘,‘the_value‘,{到期:7,路徑:‘/‘,域名:‘jquery.com“,安全:真});
 * @desc    創建一個cookie與所有可用的選項。
 * @example $ .cookie(‘the_cookie‘,‘the_value‘);
 * @desc    創建一個會話cookie。
 * @example $ .cookie(‘the_cookie‘,NULL);
 * @desc    由空傳遞的值刪除的cookie。
 *
 * @param    參數字符串名稱的Cookie的名稱。
 * @param    參數字符串值的cookie的值。
 * @param    參數對象的選擇對象文本包含鍵/值對提供可選的cookie的屬性。
 * @option    號碼|日期到期一個整數從現在起指定到期日在天或Date對象。
 *            如果指定了負值(例如,在過去的日期),該cookie將被刪除。
 *            如果設置為空或省略,cookie將是一個會話cookie並不會被保留
 *            當在瀏覽器退出。
 * @option    字符串路徑的Cookie路徑屬性附加傷害值(默認值:頁面的路徑創建的cookie)。
 * @option    字符串域的cookie域屬性的值(默認值:頁面的域名創建的cookie)。
 * @option    布爾安全的,如果屬實,將Cookie的安全屬性將被設置和cookie的傳輸將
 *            需要一個安全協議(如HTTPS)。
 * @type    未定義
 *
 * @name     $ .cookie
 * @cat            插件/曲奇
 * @author    [email protected]
 */


/**
 * Get the value of a cookie with the given name.    獲取給定名字的cookie的值。
 *
 * @example $.cookie(‘the_cookie‘);
 * @desc Get the value of a cookie.                    獲取cookie的值。
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus [email protected]
 */
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(); // use expires attribute, max-age is not supported by IE
        }
        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]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + ‘=‘)) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

jQuery基於json與cookie實現購物車的方法