1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 购物车列表加载商品信息及商品增减功能(Ajax+jQuery)

购物车列表加载商品信息及商品增减功能(Ajax+jQuery)

时间:2019-05-07 03:44:11

相关推荐

购物车列表加载商品信息及商品增减功能(Ajax+jQuery)

1.功能介绍

在商品列表页面,用户将想购买的商品及想购买的数量添加进本页面的购物车列表,并计算商品价格。

2.实现思路

加载商品信息 & 修改购物车列表中的数量

服务器端:

如果用户未添加过某商品,将商品的相关信息添加进数据库中的购物车表;如果用户已经添加过某商品,则更新商品的数量;

判断用户是否登录,如果用户已登录,获取用户添加到购物车的商品信息,并将数据返回前端。

前端:

加载数据:用ajax接收后端传来的数据,并加载到前端页面;商品数量增减:为增减按钮添加单击事件,将用户修改的商品数量提交给服务器端,修改数据库中的数据,并将修改后的数据传回前端。

3.实现代码

add.php

<?php//data/cart/add.phprequire_once("./cart.php");session_start();//查询用户是否登录,如果用户已登录,则uid会存储在session中@$uid=$_SESSION["uid"];//获取商品id@$pid=$_REQUEST["pid"];//获取商品数量@$count=$_REQUEST["count"];if($uid!=null&&$pid!=null&&$count!=null){global $conn;//查询某个用户的购物车中有没有某个商品$sql="SELECT iid,count FROM knewone_shoppingcart_item WHERE uid=$uid AND lid=$pid";$result=mysqli_query($conn,$sql);$row=mysqli_fetch_row($result);if($row==null){ //如果没有该商品,添加商品$sql="INSERT INTO knewone_shoppingcart_item VALUES (null,$uid,$pid,$count,0)";mysqli_query($conn,$sql);}else{ //如果商品已经加入购物车$iid=$row[0]; //iid$old_count=$row[1]; //count为已经添加的商品数量update($iid,$old_count+$count); //更新操作,最新数量=已经添加的商品数量+新添加的数量};};

get.php

<?php//data/cart/get.php//商品列表页面当前用户的购物车汇总header("Content-Type:application/json"); require_once("../init.php");//需要获取用户信息,在session中session_start();@$uid=$_SESSION["uid"];//如果用户已登录if($uid!=null){ //查新商品相关信息$sql="SELECT *,(SELECT sm FROM knewone_product_details_pic WHERE pid=pid limit 1) AS sm FROM knewone_shoppingcart_item INNER JOIN knewone_product_details ON pid=lid WHERE uid=$uid"; $result=mysqli_query($conn,$sql);echo json_encode(mysqli_fetch_all($result,1));};

product.js

//加载购物车列表的商品信息function loadCart(){//确认用户是否登录,用户登录后才能添加商品到购物车$.getJSON("data/users/isLogin.php",data=>{//如果用户已登录if(data.ok==1){$.getJSON("data/cart/get.php",items=>{var html="";for(var item of items){var {iid,title,count,price}=item; //解构html+=`<div class="item"><span title="${item.title}">${item.title}</span><div><span class="reduce" data-iid="${item.iid}">-</span><input type="text" value="${item.count}"><span class="add" data-iid="${item.iid}">+</span></div><p><span>¥${(item.count*item.price).toFixed(2)}</span></p></div>`;};$("#cart>.cart_content").html(html);});}else{//如果用户未登录,跳转到登录页面location.href="login.html?back="+location.href;};});};//购物车列表商品加减$("#cart>.cart_content").on("click",".reduce,.add",function(){//this->span按钮var $span=$(this);var n=parseInt($span.siblings("input").val());if($span.is(".add"))n++;elsen--;//把n提交给服务器,在数据库中改完再传回来$.get("data/cart/update.php",{iid:$span.data("iid"),count:n}).then(()=>{loadCart();});});

更多内容,欢迎关注微信公众号“让知识成为资产”。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。