• 购物车案例


    学习前端以来,一直很好奇像京东,淘宝这种大型网站的购物车是怎么做到统一的,就去搜索了一些资料吧!大致的看了一下,自己实战了下,俗话说的好,读万卷书不如行万里路!购物车只是一个很小的案例,但也可以去动手做一做,感受下过程!积少成多!

    这案例主要是通过本地储存来实现的,我用了两种方法,一种是cookie,另一种是localStorage。cookie会跟随http发送给服务器,并且有时间限制,在没有设置时间时,默认过期时间是关闭浏览器就过期;localStorage是本地的,永久的,储存的数据也更大!这是cookie和localStorage的区别!

    !!!敲重点,我所写的都是基于原生,没有使用jQuery!

    就先用cookie来实现下效果吧!

    1. 目前没有后端,那就先自己模拟下后端传输数据;准备一个json文件,里面存放的就是数据!类似下图这样!
    2. 引入之前封装好的ajax和cookie的js文件,也可引入jQuery,但jQuery没有提供cookie的方法,只有插件,网上下一个即可!
        下面是封装ajax的代码
       1 function ajax(options){
       2     var {type,url,success,data,error,timeout}=options;
       3     data=data||{};
       4     type=type||"get";
       5     timeout=timeout||2000;
       6     var str="";
       7     for(var i in data){
       8         str+=`${i}=${data[i]}&`;
       9     }
      10     if(type=="get"){
      11         var d=new Date();
      12         url=url+"?"+str+"_yjyt="+d.getTime();
      13     }
      14     var xhr=new XMLHttpRequest();
      15     xhr.open(type,url);
      16     // console.log(url);
      17     xhr.onreadystatechange=function(){
      18         if(xhr.readyState==4&&xhr.status==200){
      19             success&&success(xhr.responseText);
      20             error=null;
      21         }else if(xhr.readyState==4&&xhr.status!=200){
      22             error&&error(xhr.status);
      23             success=null;
      24             error=null;
      25         }
      26     }
      27     setTimeout(()=>{
      28         error&&error(timeout);;
      29         success=null;
      30     },timeout);
      31     if(type=="post"){
      32         xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      33         xhr.send(str);
      34     }else{
      35         xhr.send();
      36     }
      37 }

       接下来的是cookie的代码

       1 function setCookie(key, val, options) {
       2     // console.log(options.expires);
       3     options = options || {};
       4     var path = "";
       5     if (options.path) {
       6         path = ";path=" + options.path;
       7     }
       8     var expires = "";
       9     if (options.expires) {
      10         var d = new Date();
      11         d.setDate(d.getDate() + options.expires);
      12         expires = ";expires=" + d;
      13         console.log(expires);
      14     }
      15     document.cookie = key + "=" + val + path + expires;
      16 }
      17 function getCookie(key) {
      18     // var arr=document.cookie;
      19     // console.log(arr);
      20     var arr = document.cookie.split(";");
      21     console.log(arr);
      22     for (var i = 0; i < arr.length; i++) {
      23         if (arr[i].split("=")[0] === key) {
      24             return arr[i].split("=")[1];
      25         }
      26     }
      27     return "";
      28 }
      29 function removeCookie(key, options) {
      30     options = options || {};
      31     options.expires = -1;
      32     // console.log(options);
      33     // console.log(key);
      34     setCookie(key, 23, options);
      35 }
    3. 接下来就是布局,简单点来,感受下就好,不好看可以自己后期通过css改,这都是写小问题哈,我只说关键的地方!布局简陋,可以自行发挥哦!
      显示商品列表的布局
      1     <h2>这是商品列表<a href="car-local.html">去结算</a></h2>
      2     <div class="cont">
      3         <p>不好意思,卖完了!</p>
      4     </div>

       购物车的布局

       1     <h2>这是结算页<a href="shop.html">继续购物</a></h2>
       2     <table border="1" rules="all" width="900" align="center">
       3         <thead>
       4             <tr>
       5                 <th>图片</th>
       6                 <th>名字</th>
       7                 <th>价格</th>
       8                 <th>数量</th>
       9                 <th>操作</th>
      10             </tr>
      11         </thead>
      12         <tbody></tbody>
      13     </table>
    4. 下面就到我们最关键得到部分了,我们先要获取到用户点击了那个商品的假如购物车,然后要获取数量,再保存进cookie里,然后拿到cookie中的数据渲染购物车的页面,这么一说感觉很简单是吧,来,上代码感受下!
      先获取数据保存到cookie
       1 <script src="js/ajax.js"></script>
       2 <script src="js/cookie.js"></script>
       3 <script>
       4     class Shop {
       5         constructor() {
       6             this.url = "http://localhost/test/shopping/data/goods.json";
       7             this.cont = document.querySelector(".cont");
       8             this.init();
       9             this.addEvent();
      10         }
      11         init() {
      12             ajax({
      13                 url: this.url,
      14                 success: res => {
      15                     this.res = JSON.parse(res);
      16                     this.display()
      17                 }
      18             })
      19         }
      20         display() {
      21             var str = "";
      22             for (var i = 0; i < this.res.length; i++) {
      23                 str += `<div class="box" index="${this.res[i].goodsId}">
      24                             <img src="${this.res[i].img}" alt="">
      25                             <p>${this.res[i].name}</p>
      26                             <span>${this.res[i].price}</span>
      27                             <input type="button" value="加入购物车">
      28                         </div>`;
      29             }
      30             this.cont.innerHTML = str;
      31         }
      32         addEvent() {
      33             var that = this;
      34             this.cont.addEventListener("click", function (eve) {
      35                 var e = eve || window.event;
      36                 var target = e.target || e.srcElement;
      37                 if (target.type === "button") {
      38                     that.id = target.parentNode.getAttribute("index");
      39                     that.setcookie();
      40                 }
      41             });
      42         }
      43         setcookie() {
      44             this.goods = getCookie("goods") ? JSON.parse(getCookie("goods")) : [];
      45             if (this.goods.length < 1) {
      46                 this.goods.push({
      47                     id: this.id,
      48                     num: 1
      49                 });
      50             } else {
      51                 var onoff = 1;
      52                 for (var i = 0; i < this.goods.length; i++) {
      53                     if (this.goods[i].id == this.id) {
      54                         this.goods[i].num++;
      55                         onoff = 0;
      56                     }
      57                 }
      58                 if (onoff == 1) {
      59                     this.goods.push({
      60                         id: this.id,
      61                         num: 1
      62                     })
      63                 }
      64             }
      65             setCookie("goods", JSON.stringify(this.goods));
      66         }
      67     }
      68     new Shop;
      69 </script>
      拿到cookie的数据渲染购物车
       1 <script src="js/ajax.js"></script>
       2 <script src="js/cookie.js"></script>
       3 <script>
       4     class Car {
       5         constructor() {
       6             // 数据
       7             this.url = "http://localhost/test/shopping/data/goods.json";
       8             this.tbody = document.querySelector("tbody");
       9             this.init();
      10             // 绑定事件
      11             this.addEvent();
      12         }
      13         addEvent() {
      14             var that = this;
      15             // 事件委托
      16             this.tbody.addEventListener("click", function (eve) {
      17                 var e = eve || window.event;
      18                 var target = e.target || e.srcElement;
      19                 if (target.tagName === "SPAN") {
      20                     that.id = target.parentNode.parentNode.getAttribute("index");
      21                     target.parentNode.parentNode.remove();
      22                     that.removecookie();
      23                 }
      24             });
      25             this.tbody.addEventListener("input", function (eve) {
      26                 var e = eve || window.event;
      27                 var target = e.target || e.srcElement;
      28                 if (target.type === "number") {
      29                     // console.log(target.value);
      30                     that.id = target.parentNode.parentNode.getAttribute("index");
      31                     that.val = target.value;
      32                     that.updatecookie();
      33                 }
      34             })
      35         }
      36         updatecookie() {
      37             var i = 0;
      38             var onoff = this.goods.some((val, index) => {
      39                 i = index;
      40                 return val.id == this.id;
      41             });
      42             if (onoff) {
      43                 this.goods[i].num = this.val;
      44             }
      45             setCookie("goods", JSON.stringify(this.goods));
      46         }
      47         removecookie() {
      48             var i = 0;
      49             var onoff = this.goods.some((val, index) => {
      50                 i = index;
      51                 return val.id == this.id;
      52             });
      53             if (onoff) {
      54                 this.goods.splice(i, 1);
      55             }
      56             setCookie("goods", JSON.stringify(this.goods));
      57         }
      58         init() {
      59             var that = this;
      60             ajax({
      61                 url: this.url,
      62                 success: function (res) {
      63                     that.res = JSON.parse(res);
      64                     // console.log(that.res);
      65                     that.getcookie();
      66                 }
      67             })
      68         }
      69         getcookie() {
      70             this.goods = getCookie("goods") ? JSON.parse(getCookie("goods")) : [];
      71             // console.log(this.goods);
      72             this.display();
      73         }
      74         // 渲染页面
      75         display() {
      76             var str = "";
      77             for (var i = 0; i < this.res.length; i++) {
      78                 for (var j = 0; j < this.goods.length; j++) {
      79                     if (this.res[i].goodsId == this.goods[j].id) {
      80                         str += `<tr index="${this.goods[j].id}">
      81                                     <td><img src="${this.res[i].img}"></td>
      82                                     <td>${this.res[i].name}</td>
      83                                     <td>${this.res[i].price}</td>
      84                                     <td><input type="number" value="${this.goods[j].num}" min=1 /></td>
      85                                     <td><span>删除</span></td>
      86                                 </tr>`;
      87                     }
      88                 }
      89             }
      90             this.tbody.innerHTML = str;
      91         }
      92     }
      93 
      94     new Car;
      95 </script>

     以上就是cookie方法实现购物车的代码!下面我来说下用localStorage方法实现吧,其实布局什么都是一样的,只是把cookie改成localStorage就可以了。我就只放js的代码了哦

    商品列表的js

     1     class shop {
     2         constructor() {
     3             this.cont = document.querySelector(".cont");
     4             this.url = "http://localhost/test/shopping/data/goods.json";
     5             this.init();
     6             this.addEvent();
     7         }
     8         init() {
     9             ajax({
    10                 url: this.url,
    11                 success: (res) => {
    12                     this.res = JSON.parse(res);
    13                     this.display();
    14                 }
    15             })
    16         }
    17         display() {
    18             var str = "";
    19             for (var i = 0; i < this.res.length; i++) {
    20                 str += `<div class="box" index="${this.res[i].goodsId}">
    21                             <img src="${this.res[i].img}" alt="">
    22                             <p>${this.res[i].name}</p>
    23                             <span>${this.res[i].price}</span>
    24                             <input type="button" value="加入购物车">
    25                         </div>`;
    26             }
    27             this.cont.innerHTML = str;
    28         }
    29         addEvent() {
    30             var that = this;
    31             this.cont.addEventListener("click", function (eve) {
    32                 var e = eve || window.event;
    33                 var target = e.target || e.srcElement;
    34                 if (target.type === "button") {
    35                     that.id = target.parentNode.getAttribute("index");
    36                     that.setStorage();
    37                 }
    38             })
    39         }
    40         setStorage() {
    41             this.goods = JSON.parse(localStorage.getItem("goods")) || [];
    42             // console.log(this.goods.length);
    43             // console.log(this.goods);
    44             if (this.goods.length < 1) {
    45                 this.goods.push({
    46                     id: this.id,
    47                     num: 1
    48                 });
    49             } else {
    50                 var onoff = 1;
    51                 for (var i = 0; i < this.goods.length; i++) {
    52                     if (this.id == this.goods[i].id) {
    53                         // console.log(this.arr[i])
    54                        this.goods[i].num++;
    55                        onoff=0;
    56                     }
    57                     if (onoff) {
    58                         this.goods.push({
    59                             id: this.id,
    60                             num: 1
    61                         });
    62                     }
    63                 }
    64             }
    65             localStorage.setItem("goods", JSON.stringify(this.goods));
    66             // console.log(this.goods.length);
    67             // this.goods=localStorage.getItem("id");
    68             // console.log(this.goods);
    69         }
    70     }
    71     new shop;

    购物车的

     1     class Car {
     2         constructor() {
     3             this.tbody = document.querySelector("tbody");
     4             this.url = "http://localhost/test/shopping/data/goods.json";
     5             this.goods = JSON.parse(localStorage.getItem("goods"));
     6             // console.log(this.goods);
     7             this.init();
     8             this.addEvent();
     9         }
    10         addEvent() {
    11             var that = this;
    12             this.tbody.addEventListener("click", function (eve) {
    13                 var e = eve || window.event;
    14                 var target = e.target || e.srcElement;
    15                 if (target.tagName === "SPAN") {
    16                     that.id = target.parentNode.parentNode.getAttribute("index");
    17                     // console.log(that.id);
    18                     target.parentNode.parentNode.remove();
    19                     that.removeLocal();
    20                 }
    21             });
    22             this.tbody.addEventListener("input",function(eve){
    23                 var e=eve||window.event;
    24                 var target=e.target||e.srcElement;
    25                 if(target.type==="number"){
    26                     that.id = target.parentNode.parentNode.getAttribute("index");
    27                     // console.log(that.id);
    28                     that.val=target.value;
    29                     that.updateLocal();
    30                 }
    31             })
    32         }
    33         updateLocal(){
    34             var i=0;
    35             var onoff=this.goods.some((val,index)=>{
    36                 i=index;
    37                 return val.id=this.id;
    38             });
    39             if(onoff){
    40                 this.goods[i].num=this.val;
    41             }
    42             localStorage.setItem("goods",JSON.stringify(this.goods));
    43         }
    44         removeLocal() {
    45             var i=0;
    46             var onoff=this.goods.some((val,index)=>{
    47                 i=index;
    48                 return val.id=this.id;
    49             });
    50             if(onoff){
    51                 this.goods.splice(i,1);
    52             }
    53             localStorage.setItem("goods",JSON.stringify(this.goods));
    54         }
    55         init() {
    56             ajax({
    57                 url: this.url,
    58                 success: (res) => {
    59                     this.res = JSON.parse(res);
    60                     // console.log(this.res);
    61                     this.display();
    62                 }
    63             });
    64         }
    65         display() {
    66             var str = "";
    67             for (var i = 0; i < this.res.length; i++) {
    68                 for (var j = 0; j < this.goods.length; j++) {
    69                     if (this.res[i].goodsId === this.goods[j].id) {
    70                         // console.log(1);
    71                         str += `<tr index="${this.goods[j].id}">
    72                                     <td><img src="${this.res[i].img}"></td>
    73                                     <td>${this.res[i].name}</td>
    74                                     <td>${this.res[i].price}</td>
    75                                     <td><input type="number" value="${this.goods[j].num}" min=1 /></td>
    76                                     <td><span>删除</span></td>
    77                                 </tr>`;
    78 
    79                     }
    80                 }
    81             }
    82             this.tbody.innerHTML = str;
    83         }
    84     }
    85     new Car;

    上面是用localStorage的方法实现的购物车。

    以上是我用两种方法实现购物车的代码,效果上是没有区别的,cookie更为浪费性能一些,可以两种都试下。

  • 相关阅读:
    Windows 7 64位中安装IIS失败?“出现错误。并非所有的功能被成功更改”
    Android模拟器调试网络通讯
    大智慧日K线的数据结构
    如何在浏览器看到ASP的错误详细信息(IIS7.0)
    Eclipse快捷键指南
    【幾百年沒有遇到的問題】数据库"***"的媒体集有两个家族成员,但只提供了一个,必须提供所有的成员
    [轉載]用绩效模型对IT技术人员进行有效管理
    Microsoft VBScript 运行时错误 错误 '800a000d' 类型不匹配: 'regEx.Replace'
    QQ2010在win7中安装时如何把个人文件保存于安装目录下
    超经典!90后看不懂的操作系统
  • 原文地址:https://www.cnblogs.com/ruo-shui-yi-fang/p/11564124.html
Copyright © 2020-2023  润新知