静态HTML网页可以实现购物车功能吗?而且不用数据库...

静态HTML网页可以实现购物车功能吗?而且不用数据库...,第1张

一般购物车用session或者cookie实现。如果要实现session,HTML是不可能

如果用cookie可以用js来做。理论上是可以实现。但没多少人做这种事情。

可能是因为这样对用户的认证是一大问题,正常点的网站不可能不实行用户认证的。

不过退一步,用flash做的话,不但变量保存问题可以比较容易解决,网页效果也会好很多。当然,步骤稍微麻烦点,技术要求高点。

通常不会用mailto来发邮件。除非你只想发几句话。稍微大一点的文本就发不了了。

页面jsp :

<%@ page language="java" contentType="text/html charset=utf-8"

    pageEncoding="utf-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html charset=utf-8" />

<title>易买网 - 首页</title>

<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath }/css/style.css" />

<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-2.1.1.js"></script>

<script type="text/javascript">

var contextPath = '${pageContext.request.contextPath }'

</script>

<script type="text/javascript" src="${pageContext.request.contextPath }/js/shopping.js"></script>

</head>

<body>

<jsp:include page="top.jsp" />

<div id="position" class="wrap">

您现在的位置:<a href="Home">易买网</a> &gt 购物车

</div>

<div class="wrap">

<div id="shopping">

<form action="" method="post">

<table>

<tr>

<th>商品名称</th>

<th>商品价格</th>

<th>购买数量</th>

<th> *** 作</th>

</tr>

<c:forEach items="${sessionScope.shopCar}"  var="item" varStatus="status">

<tr id="product_id_${item.proId}">

<td class="thumb"><img src="${item.proImg }" height="50" width="30" /><a href="Product?action=view&entityId=${item.proId}">${item.proName}</a></td>

<td class="price" id="price_id_1">

<span><fmt:formatNumber value="${item.proPrice}" type="NUMBER" minFractionDigits="2" /></span>

<input type="hidden" value="${item.proPrice}" />

</td>

<td class="number">

<dl>

<dt><span onclick="sub('number_id_${item.proId}','${item.proId}')">-</span><input id="number_id_${item.proId}" type="text" readonly="readonly" name="number" value="${item.proNum}" /><span onclick="addNum('number_id_${item.proId}','${item.proId}')">+</span></dt>

</dl>

</td>

<td class="delete"><a href="javascript:deleteItem('product_id_${item.proId}','${item.proId}')">删除</a></td>

</tr>

</c:forEach>

</table>

<div class="button"><input type="submit" value="" /></div>

</form>

</div>

</div>

<div id="footer">

Copyright &copy  kaka qq 292817678 itjob  远标培训. 

</div>

</body>

</html>

页面关联的js 自己去网上下载一个jquery

/*数量减少*/

function sub(id,proId){

//购买数量的值

var num = $('#'+id).val()

if(num > 1){

$('#'+id).val(num - 1)

}

edit(id,proId)

}

function edit(id,proId){

var url = contextPath + '/HomeCarManager'

//修改后的数量,购物明细的商品的id

num = $('#'+id).val()

$.post(url,{"num":num,"proId":proId},function (msg){

/*

if(msg == 'true'){

alert('修改成功')

} else {

alert('修改失败')

}*/

})

}

/**

 * 数量增加

 * @param {} id

 */

function addNum(id,proId){

//购买数量的值

var num = $('#'+id).val()

$('#'+id).val(parseInt(num) + 1)

edit(id,proId)

}

/**

 * 删除购物明细

 */

function deleteItem(trId,proId){

//

//console.log($("#"+trId))

//js删除页面节点

//$("#"+trId).remove()

var url = contextPath + '/HomeCarManager'

$.post(url,{"proId":proId},function (msg){

if(msg == 'true'){

//js删除页面节点

$("#"+trId).remove()

}

})

}

后台servlet1

package com.kaka.web

import java.io.IOException

import java.io.PrintWriter

import java.util.ArrayList

import java.util.List

import javax.servlet.ServletException

import javax.servlet.http.HttpServlet

import javax.servlet.http.HttpServletRequest

import javax.servlet.http.HttpServletResponse

/**

 * 购物车处理类

 * @author @author ITJob 远标培训

 *

 */

import com.kaka.entity.Items

import com.kaka.entity.Product

import com.kaka.service.ProductService

import com.kaka.service.impl.ProductServiceImpl

public class HomeCar extends HttpServlet {

private static final long serialVersionUID = 1L

ProductService ps = new ProductServiceImpl()

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//获取商品的id

String proId = req.getParameter("proId")

resp.setContentType("text/htmlcharset=UTF-8")

PrintWriter writer = resp.getWriter()

if(null != proId && !"".equals(proId)){

//返回添加购物车成功

//System.out.println("=============" + proId)

//根据商品的id查询商品

try {

Integer pId = Integer.parseInt(proId)

Product product = ps.findProductById(pId)

if(null != product){

//查询到了商品,将商品的相关参数构建一个购物明细放入到购物车

Items it = new Items()

it.setProId(product.getProId())

it.setProName(product.getProName())

it.setProPrice(product.getProPrice())

it.setProImg(product.getProImg())

//先判断session范围是否有购物车

List<Items> shopCar = (List<Items>)req.getSession().getAttribute("shopCar")

if(null == shopCar){

//购物车

shopCar = new ArrayList<Items>()

}

//将商品加入到购物车之前,判断购物车中是否已经包含了该购物明细,如果包含了,只需要修改购买的数量

if(shopCar.contains(it)){

int index  = shopCar.indexOf(it)//寻找购物车中包含购物明细在购物车中位置

Items items = shopCar.get(index)//获取购物车中存在的购物明细

items.setProNum(items.getProNum()+1)

} else {

shopCar.add(it)

}

//将购物车放入到session访问

req.getSession().setAttribute("shopCar", shopCar)

//返回

writer.print(true)

} else {

writer.print(false)

}

} catch (Exception e) {

e.printStackTrace()

writer.print(false)

}

} else {

writer.print(false)

}

writer.flush()

writer.close()

}

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doPost(req, resp)

}

}

后台管理servlet

package com.kaka.web

import java.io.IOException

import java.io.PrintWriter

import java.util.ArrayList

import java.util.List

import javax.mail.FetchProfile.Item

import javax.servlet.ServletException

import javax.servlet.http.HttpServlet

import javax.servlet.http.HttpServletRequest

import javax.servlet.http.HttpServletResponse

/**

 * 购物车修改

 * @author ITJob 远标培训

 *

 */

import com.kaka.entity.Items

import com.kaka.entity.Product

import com.kaka.service.ProductService

import com.kaka.service.impl.ProductServiceImpl

public class HomeCarManager extends HttpServlet {

private static final long serialVersionUID = 1L

ProductService ps = new ProductServiceImpl()

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

resp.setContentType("text/htmlcharset=UTF-8")

PrintWriter writer = resp.getWriter()

//获取参数

String proId = req.getParameter("proId")

String num = req.getParameter("num")

if(null != proId && null != num

&& !"".equals(proId) && !"".equals(num)){

try {

Integer pId = Integer.parseInt(proId)

Float pNum = Float.parseFloat(num)

//根据商品的id获取对应的明细项

// 先判断session范围是否有购物车

List<Items> shopCar = (List<Items>) req.getSession().getAttribute("shopCar")

for(Items it : shopCar){

if(it.getProId()== pId){

it.setProNum(pNum)

}

}

writer.print(true)

} catch (Exception e) {

e.printStackTrace()

}

} else {

//删除的 *** 作

try {

Integer pId = Integer.parseInt(proId)

//根据商品的id获取对应的明细项

// 先判断session范围是否有购物车

List<Items> shopCar = (List<Items>) req.getSession().getAttribute("shopCar")

Items items = null

for(Items it : shopCar){

if(it.getProId()== pId){

items = it

break

}

}

if(null != items){

shopCar.remove(items)

req.getSession().setAttribute("shopCar",shopCar)

}

writer.print(true)

} catch (Exception e) {

e.printStackTrace()

}

}

writer.flush()

writer.close()

}

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doPost(req, resp)

}

}

html中的购物车的增减不能直接传送到后台,可以通过ajax,在js中发送ajax

纯前端的话可以参考下面的

<!DOCTYPE html>    

<html lang="en">    

<head>    

<meta charset="UTF-8">    

<title>cart</title>    

<style type="text/css">

    body,p,a,input{

    margin: 0

    padding: 0

    font-size: 12px

}

.container{

    width: 100%

}

.main{

    width: 1000px

    height: 500px

    margin:100px auto

}

.main .cart-container table{

    width: 100%

}

.main .cart-container table tr{

    text-align: center

}

.main .cart-container table tr:hover{

    background: rgba(128, 128, 128, 0.2)

}

.main .cart-container table .table-header{

    height: 30px

    background: #d9d9d9

    font-size: 1.2em

}

.main .cart-container table .table-header td:first-child{

    border-left: solid 4px red

    box-sizing: border-box

}

.main .cart-container table tr td:nth-child(1),

.main .cart-container table tr td:nth-child(2){

    text-align: left

}

.main .cart-container table tr td:nth-child(2){

    width: 52%

}

.main .cart-container table tr td:nth-child(3){

    width: 12%

}

.main .cart-container table tr td:nth-child(4){

    width: 12%

}

.main .cart-container table tr td:nth-child(5){

    width: 12%

}

.main .cart-container table tr td:last-child{

    width: 10%

}

.cart-good{

    height: 60px

}

.cart-good img{

    float: left

    margin: 10px

    width: 60px

}

.cart-good td p{

    margin: 10px 0px

}

/*加、减按钮*/

.cart-good td input[type='button']{

     width: 20px

     height: 20px

     background: #00f300

     outline: none

     border: none

 }

.cart-good td input[type='button']:disabled{

    background: grey

}

.cart-good td input[type='button']:first-child{

   margin-right: -4px

}

.cart-good td input[type='button']:last-child{

    margin-left: -4px

}

.cart-good td input[type='text']{

    width: 30px

    height: 20px

    outline: none

    border: none

    text-align: center

}

.table-footer{

    display: flex

    justify-content: space-between

    line-height: 40px

}

.table-footer div{

    font-size: 1.2em

}

.table-footer div button{

    background: red

    width: 120px

    height: 40px

    color: white

}

</style>  

</head>    

<body>    

<div class="container">    

<header></header>    

<section class="main">    

<div class="cart-container">    

<table cellspacing="0">    

<tr class="table-header">    

<td><input type="checkbox" id="chk_alla"></td>    

<td>聚美优品发货</td>    

<td>聚美价</td>    

<td>数量</td>    

<td>小计</td>    

<td> *** 作</td>    

</tr>    

<!--<tr class="cart-good">-->    

<!--<td><input type="checkbox" id="001"></td>-->    

<!--<td>-->    

<!--<img src="https://p2.jmstatic.com/product/001/293/1293263_std/1293263_60_60.jpg" alt="">-->    

<!--<p>[极速免税]PITTA MASK 口罩3枚入</p>-->    

<!--<p>型号:新版防晒款  容量:3枚入</p>-->    

<!--</td>-->    

<!--<td>89.00</td>-->    

<!--<td>-->    

<!--<input type="button" value="-">-->    

<!--<input type="text" value="1">-->    

<!--<input type="button" value="+">-->    

<!--</td>-->    

<!--<td>89.00</td>-->    

<!--<td><a href="#">删除</a></td>-->    

<!--</tr>-->    

</table>    

<div class="table-footer">    

<div>    

<input type="checkbox" id="chk_allb"> <label for="chk_allb">全选</label>    

<span style="margin-left: 20px">继续购物 | 清空选中商品</span>    

</div>    

<div>    

共 <span id="good_count">5</span>件商品    商品应付总额:<span id="goods_total">¥229.00</span>    

<button class="btn_menu">去结算</button>    

</div>    

</div>    

</div>    

</section>    

</div>    

<script>

(function () {

    var skin_products= [

        {

            "id":"002",

            "title": "Estee Lauder 多效智妍精华霜15ml",

            "img_url": "http://p0.jmstatic.com/product/003/565/3565880_std/3565880_350_350.jpg",

            "price": 249.0,

            "number":6,

            "acount": "520",

            "ischecked":true

        },

        {

            "id":"004",

            "title": "EsteeLauder 肌透修护洁面乳30ml",

            "img_url": "http://p4.jmstatic.com/product/003/155/3155764_std/3155764_350_350.jpg",

            "price": 49.9,

            "number":1,

            "acount": "5911",

            "ischecked":false

        },

        {

            "id":"008",

            "title": "雅诗兰黛无痕持妆粉底液",

            "img_url": "http://p3.jmstatic.com/product/003/662/3662318_std/3662318_350_350.jpg",

            "price": 69.9,

            "number":2,

            "acount": "3972",

            "ischecked":true

        },

        {

            "id":"0012",

            "title": "Estee Lauder 肌初赋活原生液30ml",

            "img_url": "http://p4.jmstatic.com/product/003/565/3565914_std/3565914_350_350.jpg",

            "price": 159.0,

            "number":1,

            "acount": "2338"

        },

        {

            "id":"001",

            "title": "雅诗兰黛无痕持妆粉底液30ml",

            "img_url": "http://p2.jmstatic.com/product/001/648/1648502_std/1648502_350_350.jpg",

            "price": 298.0,

            "number":4,

            "acount": "5071",

            "ischecked":false

        },

        {

            "id":"009",

            "title": "雅诗兰黛眼部精华霜15ml",

            "img_url": "http://p1.jmstatic.com/product/001/049/1049746_std/1049746_350_350.jpg",

            "price": 399.0,

            "number":1,

            "acount": "4022",

            "ischecked":false

        }

    ]

//    添加商品

    function load() {

        var tbody=document.querySelector('.cart-container table tbody')

        for(let good of skin_products){

            tbody.innerHTML+=` <tr class="cart-good" id="${good.id}">

                            <td><input type="checkbox" class="good-check" ${good.ischecked?"checked":''}></td>

                            <td>

                                <img src="${good.img_url}" alt="">

                                <p>[极速免税]PITTA MASK 口罩3枚入</p>

                                <p>型号:新版防晒款  容量:3枚入</p>

                            </td>

                            <td>${good.price}</td>

                            <td>

                                <input type="button" value="-"  ${good.number<=1?"disabled":''}>

                                <input type="text" value="${good.number}">

                                <input type="button" value="+">

                            </td>

                            <td>${good.price*good.number}</td>

                            <td><a href="#">删除</a></td>

                        </tr>`

        }

        totalAcount()

    }

    load()

//    end all..........

    // 1. 为table注册单击事件

    var table01=document.querySelector('.cart-container table')

    table01.onclick=function (event) {

        var node=event.target

        if(node.getAttribute('type')=='button'){

            // alert(event.target.value)

            changeNumber(event)

            subtotal(event)

            checkedRow(event)

            checkedAllRows()

        }else if(node.className=='good-check'){

            checkedAllRows()

        }else if(node.id=='chk_alla'){

            var f=event.target.checked

            var chks=document.querySelectorAll('.good-check')

            for(var ck of chks){

                ck.checked=f

            }

            for(var good of skin_products){

                good.ischecked=f

            }

        }else if(node.nodeName.toLowerCase()=='a'){

            var tr=event.target.parentNode.parentNode

            for(var i=0i<skin_products.lengthi++){

                if(skin_products[i].id==tr.id){

                    skin_products.splice(i,1)

                    console.log(skin_products)

                }

            }

            tr.parentNode.removeChild(tr)

        }

        totalAcount()

    }

    //单击增加或减少按钮的方法

    function changeNumber(event) {

        var node=event && event.target

        var v=0

        if(node.value && node.value=='+'){

            // node.previousElementSibling.value=parseInt(node.previousElementSibling.value)+1

            node.previousElementSibling.value++

            v=node.previousElementSibling.value

            node.previousElementSibling.previousElementSibling.disabled=false

        }else{

            // if(node.value && node.value=='+')

            if(node.nextElementSibling.value>1){

                node.nextElementSibling.value--

                v=node.nextElementSibling.value

                if(v==1){

                    node.disabled=true

                }

            }

        }

    //    存储商品数量

        var id=node.parentNode.parentNode.id

        for(var good of skin_products){

            if(id==good.id){

                good.number=v

            }

        }

    }

    

//    每个商品小计的方法

    

    function subtotal(event) {

        var node=event && event.target

        // var id=node.parentNode.parentNode.id

        // for(var g of skin_products){

        //     if(g.id==id){

        //         alert(g.price)

        //     }

        // }

        // var price=;

        var price=node.parentNode.previousElementSibling.innerText

        var num=node.parentNode.children[1].value

        node.parentNode.nextElementSibling.innerText=(num*price).toFixed(2)

    }

//    检验该商品是否选中

    function checkedRow(event) {

        event.target.parentNode.parentNode.firstElementChild.firstElementChild.checked=true

        // event.target.parentNode.parentNode.cells[0].firstElementChild.checked=true

        // var tbody=event.target.parentNode.parentNode.parentNode

        // event.target.parentNode.parentNode.parentNode.rows[3].cells[0].firstElementChild.checked=true

    }

//   检查是否全选

    function checkedAllRows() {

        var chks=document.querySelectorAll('.good-check')

        var flag=true

        for(var ck of chks){

            if(!ck.checked){

                flag=false

                break

            }

        }

        document.querySelector('#chk_alla').checked=flag

    }

//    统计商品总量和总价格

    function totalAcount() {

        var total=0

        var total_price=0

        var chks=document.querySelectorAll('.good-check')

        for(var ck of chks){

            if(ck.checked){

                id=ck.parentNode.parentNode.id

                for(var good of skin_products){

                    if(id==good.id){

                        total+=~~good.number

                        total_price=total_price+(good.number*good.price)

                        good.ischecked=true

                    }

                }

            }

        }

        document.querySelector('#good_count').innerText=total

        document.querySelector('#goods_total').innerText=total_price

    }

})()

</script>    

</body>    

</html>


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/6159626.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-03-16
下一篇2023-03-16

发表评论

登录后才能评论

评论列表(0条)

    保存