HTML5 implements local storage function of shopping cart
This article mainly introduces the relevant information about HTML5 local storage to implement the shopping cart function. Friends who need it can refer to it
I was taking paternity leave at home, bored, looking at my previous projects, and suddenly found what I wrote before Shopping carts are all implemented using databases. In principle, there is no problem with database implementation of shopping carts, but it requires interaction with the database, which unintentionally reduces the efficiency of the program. Today I had a whim, if it could be implemented using HTML5 local storage, it would greatly increase program efficiency. Of course, HTML5 local storage involves the compatibility of various browsers, the size of stored data (NKB) and other issues. What needs to be explained here is: If you are doing a small or medium-sized micro mall project, then you can try to use HTML5 local stored procedures to implement a shopping cart!
This section will discuss with you how HTML5 local storage implements the shopping cart function!
It should be noted that the previous article forwarded someone else’s blog: HTML5 local storage usage. This section uses the knowledge from the previous section to implement a shopping cart!
First explain the general idea:
In a product table, the product IDs are different. Here, we use the product ID as the key value of JSON , to store shopping cart data.
The specific example is as follows:
When you click 'Add to Cart', the execution code is as follows:
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);
A rough explanation:
Pid: Product ID
color: Product color
num2: Product quantity
bat: Json object
batString: The string converted from the Json object
FOr loop: traverse all current local storage, delete the existing local storage, and re-establish the latest local storage. Of course, it is not necessary Delete, because of the Key value with the same name, the new one will overwrite the old one.
Finally, dynamic storage, the so-called dynamic, is the combination of the locally stored Key value and the product ID. That is to say: different products will be stored as different Key values, and N products will be stored as N Json strings. In the end, we just need to parse these N different strings and get a complete shopping cart!
Heehee, keep it simple!
So how can we traverse these N JSON strings? As follows:
Shopping cart loading page:
$(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); } } });
General explanation:
Traverse all local storage, requiring the key value to contain the bat sub-character It is completely different from the local storage of bat.
Convert the Json string into a Json object
and enter the product ID, product quantity, and product color .
With the product ID, product color, and product quantity, we can use JS or AJax to load our locally stored shopping cart. The specific loading method is as follows:
$.ajax(".......")
or:
JS Splicing HTML
Here: no demonstration.
OK, as of now, the entire HTML5 local storage implementation shopping cart is finished. If it is still OK, please give it a like!
Continue to improve this blog
It is mentioned above that Ajax or JS splicing is needed to complete the loading function. Now I will post the AJAX I wrote!
The JS code is as follows:
$(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>') }); });
Controller part:
##
[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 part
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'> <p class='proInfo'> <p class='thumb'> <img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/007/efe49ac52f0ed6f122efb169cba1adf9-1.jpg?x-oss-process=image/resize,p_40" class="lazy" src='" + picPath + @"' / alt="HTML5 implements local storage function of shopping cart" ></p> <p class='desc clear-both'> <p>" + productMol.productName + @"</p> <small>颜色分类:" + pcolor + @"</small> <span>¥" + Convert.ToDouble(productMol.shopprice).ToString("0.00") + @"</span> <p class='ctrl-p'> <p class='jian'></p> <p class='num'>" + num + @"</p> <p class='jia'></p> </p> </p> </p> </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 renderings are as follows:
The above is the detailed content of HTML5 implements local storage function of shopping cart. For more information, please follow other related articles on the PHP Chinese website!

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

The difference between H5 and HTML5 is: 1) HTML5 is a web page standard that defines structure and content; 2) H5 is a mobile web application based on HTML5, suitable for rapid development and marketing.

The core features of HTML5 include semantic tags, multimedia support, form enhancement, offline storage and local storage. 1. Semantic tags such as, improve code readability and SEO effect. 2. Multimedia support simplifies the process of embedding media content through and tags. 3. Form Enhancement introduces new input types and verification properties, simplifying form development. 4. Offline storage and local storage improve web page performance and user experience through ApplicationCache and localStorage.

HTML5isamajorrevisionoftheHTMLstandardthatrevolutionizeswebdevelopmentbyintroducingnewsemanticelementsandcapabilities.1)ItenhancescodereadabilityandSEOwithelementslike,,,and.2)HTML5enablesricher,interactiveexperienceswithoutplugins,allowingdirectembe

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.

H5 (HTML5) will improve web content and design through new elements and APIs. 1) H5 enhances semantic tagging and multimedia support. 2) It introduces Canvas and SVG, enriching web design. 3) H5 works by extending HTML functionality through new tags and APIs. 4) Basic usage includes creating graphics using it, and advanced usage involves WebStorageAPI. 5) Developers need to pay attention to browser compatibility and performance optimization.

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
