學習前端以來,一直很好奇像京東,淘寶這種大型網站的購物車是怎麼做到統一的,就去搜索了一些資料吧!大致的看了一下,自己實戰了下,俗話說的好,讀萬卷書不如行萬里路!購物車只是一個很小的案例,但也可以去動手做一做,感受下過程!積少成多! 這案例主要是通過本地儲存來實現的,我用了兩種方法,一種是cookie ...
學習前端以來,一直很好奇像京東,淘寶這種大型網站的購物車是怎麼做到統一的,就去搜索了一些資料吧!大致的看了一下,自己實戰了下,俗話說的好,讀萬卷書不如行萬里路!購物車只是一個很小的案例,但也可以去動手做一做,感受下過程!積少成多!
這案例主要是通過本地儲存來實現的,我用了兩種方法,一種是cookie,另一種是localStorage。cookie會跟隨http發送給伺服器,並且有時間限制,在沒有設置時間時,預設過期時間是關閉瀏覽器就過期;localStorage是本地的,永久的,儲存的數據也更大!這是cookie和localStorage的區別!
!!!敲重點,我所寫的都是基於原生,沒有使用jQuery!
就先用cookie來實現下效果吧!
- 目前沒有後端,那就先自己模擬下後端傳輸數據;準備一個json文件,裡面存放的就是數據!類似下圖這樣!
- 引入之前封裝好的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 }
- 接下來就是佈局,簡單點來,感受下就好,不好看可以自己後期通過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>
- 下麵就到我們最關鍵得到部分了,我們先要獲取到用戶點擊了那個商品的假如購物車,然後要獲取數量,再保存進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更為浪費性能一些,可以兩種都試下。