目录
第十六章:项目案例二:电商网站
章节简介
本章将通过一个完整的电商网站项目案例,深入讲解商品列表页与详情页的开发、购物车功能的实现,以及支付接口的对接。通过本章的学习,您将能够掌握如何设计和开发一个功能完善的电商网站。
1. 商品列表页与详情页开发
1.1 商品列表页
商品列表页是电商网站的核心页面之一,展示商品的基本信息(如名称、价格、图片等),并支持分页、筛选和排序功能。
1.2 前端实现
-
数据获取: 使用AJAX或Fetch API从后端获取商品列表数据。
javascript深色版本
fetch('/api/products') .then(response => response.json()) .then(data => { // 渲染商品列表 const productList = data.map(product => ` <div class="product-item"> <img src="${product.image}" alt="${product.name}"> <h3>${product.name}</h3> <p>Price: $${product.price}</p> <button data-id="${product.id}">Add to Cart</button> </div> `).join(''); document.getElementById('product-list').innerHTML = productList; }); -
分页功能: 在后端实现分页逻辑,并通过前端动态加载更多商品。
javascript深色版本
function loadMoreProducts(page) { fetch(`/api/products?page=${page}`) .then(response => response.json()) .then(data => { // 将新商品追加到列表中 }); } -
筛选与排序: 提供筛选条件(如价格区间、分类)和排序选项(如按价格升序/降序)。
1.3 后端实现
- API设计:
- 获取商品列表:
GET /api/products - 获取单个商品详情:
GET /api/products/:id
- 获取商品列表:
- 数据库查询优化: 使用索引提升查询性能,支持分页和过滤条件。
2. 购物车功能实现
2.1 功能概述
购物车功能允许用户添加商品、修改数量、删除商品,并计算总价。
2.2 前端实现
-
本地存储购物车数据: 使用LocalStorage或SessionStorage临时保存购物车内容。
javascript深色版本
function addToCart(productId, quantity) { let cart = JSON.parse(localStorage.getItem('cart')) || {}; cart[productId] = (cart[productId] || 0) + quantity; localStorage.setItem('cart', JSON.stringify(cart)); } function getCartItems() { return JSON.parse(localStorage.getItem('cart')) || {}; } -
渲染购物车页面: 根据购物车数据动态生成商品列表,并显示总价。
javascript深色版本
function renderCart() { const cart = getCartItems(); if (!Object.keys(cart).length) { document.getElementById('cart-items').innerHTML = '<p>Your cart is empty.</p>'; return; } fetch('/api/products') .then(response => response.json()) .then(data => { const products = data.filter(product => cart[product.id]); const cartList = products.map(product => ` <div class="cart-item"> <img src="${product.image}" alt="${product.name}"> <h3>${product.name}</h3> <p>Quantity: ${cart[product.id]}</p> <p>Subtotal: $${product.price * cart[product.id]}</p> <button onclick="removeFromCart(${product.id})">Remove</button> </div> `).join(''); document.getElementById('cart-items').innerHTML = cartList; const totalPrice = products.reduce((sum, product) => sum + product.price * cart[product.id], 0); document.getElementById('total-price').textContent = `Total: $${totalPrice}`; }); }
2.3 后端实现
- 持久化购物车数据: 如果需要跨设备或会话保存购物车内容,可以将数据存储在数据库中,并与用户账号关联。
3. 支付接口对接
3.1 支付流程
- 用户提交订单,选择支付方式。
- 前端调用支付接口,跳转到支付页面。
- 支付完成后,回调通知后端更新订单状态。
3.2 支付接口选型
- 国内常用支付接口:
- 微信支付
- 支付宝支付
- 国际支付接口:
- PayPal
- Stripe
3.3 示例:对接支付宝支付
-
申请支付接口: 在支付宝开放平台注册应用,获取App ID和密钥。
-
前端调用支付接口: 前端发起请求,获取支付参数,并跳转到支付页面。
javascript深色版本
async function payOrder(orderId) { const response = await fetch(`/api/pay/${orderId}`); const paymentData = await response.json(); // 调用支付宝支付SDK window.AlipayJSBridge.call('tradePay', paymentData, function(result) { if (result.resultCode === '9000') { alert('Payment successful!'); } else { alert('Payment failed.'); } }); } -
后端生成支付参数: 使用支付宝提供的SDK生成支付签名和参数。
javascript深色版本
const alipaySdk = require('alipay-sdk').default; const client = new alipaySdk({ appId: 'your_app_id', privateKey: 'your_private_key', alipayPublicKey: 'alipay_public_key', gateway: 'https://openapi.alipay.com/gateway.do' }); const paymentParams = await client.exec('alipay.trade.page.pay', { outTradeNo: orderId, totalAmount: orderTotal, subject: 'Order Payment', productCode: 'FAST_INSTANT_TRADE_PAY' }); res.json(paymentParams); -
支付回调处理: 支付完成后,支付宝会发送异步通知到指定的回调URL,后端需验证通知参数并更新订单状态。
学习收获
完成本章后,您将能够:
- 开发商品列表页与详情页,支持分页、筛选和排序功能。
- 实现购物车功能,包括商品添加、数量修改和总价计算。
- 对接支付接口,完成订单支付流程。
继续学习下一章,我们将探讨更多实际项目中的技术细节!

被折叠的 条评论
为什么被折叠?



