HTML5 本地存储实现购物车功能

在家休陪产假,无聊,看自己以前的项目,突然发现之前写的购物车都是用数据库实现的,数据库实现购物车原则上没什么问题,但是需要和数据库交互,这样无意之间降低了程序的效率。今天突发奇想,如果能用HTML5本地存储实现,就会大大增高程序效率。当然,HTML5 本地存储涉及到各个浏览器的兼容性,涉及存储数据的大小(NKB)等问题。在这儿需要说明的是:如果你做一个不大不小的微商城项目,那么你可以尝试使用HTML5本地存储过程实现购物车!

本节和大家探讨下HTML5本地存储实现购物车的功能!

需要说明的是:上篇转发了别人的博客:HTML5本地存储用法,本节利用上节知识实现购物车!

首先讲解下大致思路:

当你点击‘加入购物车’时,执行代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
var pid = $("#hidpid").val();
       var color = $("#Procolor").val();
       var num2 = $("#spanNum").html(); //����
       var bat = { "num": num2, "pid": pid, "pcolor": color };
       var batString = JSON.stringify(bat);
       var keyName = "bat" + pid;
       for (var i = 0; i < localStorage.length; i++) {
           if (localStorage.key(i) == keyName) {
               localStorage.removeItem(keyName);
           }
       }
       localStorage.setItem("bat"+pid, batString);

大致讲解下:

Pid:商品ID

color:商品颜色

num2:商品数量

bat:Json对象

batString:Json对象转化成的字符串

FOr循环:遍历当前所有本地存储,如果已存在的本地存储则删除,重新建立最新的本地存储,当然,也可以不删除,因为同名的Key值,新的会覆盖旧的。

最后,动态存储,所谓动态,就是本地存储的Key值和商品ID结合了。也就是说:不同的商品,将会存储为不同的Key值,N个商品,将会存储为N个Json字符串。最后,我们只需解析这N个不同的字符串,就会得到一个完整的购物车!

嘻嘻,简单吧!

那么怎样才能遍历这N个JSON字符串呢?如下:

购物车加载页面:

1
2
3
4
5
6
7
8
9
10
11
12
13
$(function () {
               for (var i = 0; i < localStorage.length; i++) {
                   var localValue = localStorage.getItem(localStorage.key(i));
                   var key = localStorage.key(i);
                   if (key != "bat"&&key.indexOf("bat")>=0) {
                       var obj = $.parseJSON(localValue);
                       var pid = obj.pid;
                       var num = obj.num;
                       var color = obj.pcolor;
                       console.log("商品ID:"+pid + "商品数量:" + num + "商品颜色:" + color);
                   }
               }
           });

大致讲解:

遍历所有本地存储,要求key值包含bat子字符切不同于bat的本地存储。<避免和其他系统本地存储相冲突,所以,要求Key值必须包含Bat>

将Json字符串转化为Json对象

并输入商品ID,商品数量,商品颜色。

有了商品ID,商品颜色,商品数量,那么我们就可以使用JS或者AJax来加载我们本地存储的购物车了。具体加载方法如下:

 $.ajax("...........")

或者:

JS拼接HTML

在此:不作演示。

OK,截止到现在,整个HTML5本地存储实现购物车也就讲完了,如果还可以,就点个赞吧!

继续完善本篇博客

上文中提到需要用Ajax或者JS拼接来完成加载功能,下面我将自己写的AJAX贴出来!

JS代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
$(function () {
                var carAry=new Array();
                for (var i = 0; i < localStorage.length; i++) {
                    var key = localStorage.key(i);
                    var localValue = localStorage.getItem(key);
                    if (key != "bat"&&key.indexOf("bat")>=0) {
                        var obj = $.parseJSON(localValue);
                        //var pid = obj.pid;
                        //var num = obj.num;
                        //var color = obj.pcolor;
                        //console.log("商品ID:" + pid + "商品数量:" + num + "商品颜色:" + color);
                        carAry.push(obj);
                      
                    }
                }
                //alert(carAry.length);
                var bat = { "carAry": carAry };
                $.post("/home/GetCarInfo", bat, function (data) {
                    $("#buycar").html(data);
                });
                $.post("/home/GetCarInfo2", bat, function (data) {
                    var AryStr = new Array();
                    AryStr = data.split('_');
    
                    $("#tops").html('<p>合计:¥' + AryStr[0] + '元</p><span>(共' + AryStr[1] + '件,不含运费)</span>')
                });
            });

控制器部分:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[HttpPost]
     public string GetCarInfo(Dictionary<string,string>[] carAry)
     {
         UserCarModel model = new UserCarModel();
         return model.GetCarInfo(carAry);
     }
     [HttpPost]
     public string GetCarInfo2(Dictionary<string, string>[] carAry)
     {
         UserCarModel model = new UserCarModel();
         return model.GetCarInfo(carAry,1);
     }

Model部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public string GetCarInfo(Dictionary<string, string>[] carAry,int i=0)
      {
          System.Text.StringBuilder sb = new System.Text.StringBuilder("");
          double sum = 0.00;
          if (i == 0)
          {
              //加载购物车
              if (carAry != null && carAry.Length > 0)
              {
                  sb.Append("<ul>");
                  foreach (var item in carAry)
                  {
                      string pid = item["pid"];
                      string num = item["num"];
                      string pcolor = item["pcolor"];
                      productMol = bll.GetModel(Convert.ToInt32(pid));
                      string picPath = getMainpic(productMol.mainPicNum);
                      sb.Append(@"<li class='clear-both'>
                  <div class='proInfo'>
                      <div class='thumb'>
                          <img src='" + picPath + @"' /></div>
                      <div class='desc clear-both'>
                          <p>" + productMol.productName + @"</p>
                          <small>颜色分类:" + pcolor + @"</small>
                          <span>¥" + Convert.ToDouble(productMol.shopprice).ToString("0.00") + @"</span>
                          <div class='ctrl-div'>
                              <div class='jian'></div>
                              <div class='num'>" + num + @"</div>
                              <div class='jia'></div>
                          </div>
                      </div>
                  </div>
              </li>");
                  }
                  sb.Append("</ul>");
              }
              else
              {
                  sb.Append("<ul><li onclick='gobuy2()'>请选择所需购买的商品</li><br/></ul>");
              }
          }
          else
          {
              //计算总金额和商品数量
              if (carAry != null && carAry.Length > 0)
              {
                  foreach (var item in carAry)
                  {
                      string pid = item["pid"];
                      string num = item["num"];
                      productMol = bll.GetModel(Convert.ToInt32(pid));
                      sum += Convert.ToDouble(productMol.shopprice) * Convert.ToDouble(num);
                  }
              }
              sb.Append(sum.ToString("0.00") + "_" + carAry.Length);
          }
          return sb.ToString();
      }
© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容