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

來源:互聯網
上載者:User

標籤:布爾   沒有   encodeuri   品種   eset   int   add   var   break   

/**     * 添加商品及數量到購物車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    克勞斯Hartl/[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 Hartl/[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實現購物車的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.