search
HomeWeb Front-endH5 TutorialHTML5 implements local storage function of shopping cart

HTML5 implements local storage function of shopping cart

Sep 09, 2017 am 11:58 AM
h5html5shopping 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(&#39;_&#39;);
    
                    $("#tops").html(&#39;<p>合计:¥&#39; + AryStr[0] + &#39;元</p><span>(共&#39; + AryStr[1] + &#39;件,不含运费)</span>&#39;)
                });

            });

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=&#39;clear-both&#39;>
                    <p class=&#39;proInfo&#39;>
                        <p class=&#39;thumb&#39;>
                            <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=&#39;" + picPath + @"&#39; / alt="HTML5 implements local storage function of shopping cart" ></p>
                        <p class=&#39;desc clear-both&#39;>
                            <p>" + productMol.productName + @"</p>
                            <small>颜色分类:" + pcolor + @"</small>
                            <span>¥" + Convert.ToDouble(productMol.shopprice).ToString("0.00") + @"</span>
                            <p class=&#39;ctrl-p&#39;>
                                <p class=&#39;jian&#39;></p>
                                <p class=&#39;num&#39;>" + num + @"</p>
                                <p class=&#39;jia&#39;></p>
                            </p>
                        </p>
                    </p>
                </li>");
                    }
                    sb.Append("</ul>");
                }
                else
                {
                    sb.Append("<ul><li onclick=&#39;gobuy2()&#39;>请选择所需购买的商品</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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5 Code: Accessibility and Semantic HTMLH5 Code: Accessibility and Semantic HTMLApr 09, 2025 am 12:05 AM

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.

Is h5 same as HTML5?Is h5 same as HTML5?Apr 08, 2025 am 12:16 AM

"h5" and "HTML5" are the same in most cases, but they may have different meanings in certain specific scenarios. 1. "HTML5" is a W3C-defined standard that contains new tags and APIs. 2. "h5" is usually the abbreviation of HTML5, but in mobile development, it may refer to a framework based on HTML5. Understanding these differences helps to use these terms accurately in your project.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version