您的位置:首页 > Web前端 > JQuery

jQuery基于json与cookie实现购物车的方法

2017-06-02 12:22 357 查看
/**
* 添加商品及数量到购物车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/klaus.hartl@stilbuero.de
*/

/**
* 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/klaus.hartl@stilbuero.de
*/
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: