由于创建一个完整的购物商城需要大量的代码,并且涉及前端、后端、数据库、支付接口等复杂系统,我将为您提供一个简化的示例来说明如何使用不同的编程语言来实现一个基本的购物商城功能。
Python (Flask) 后端示例
python
from flask import Flask, request, jsonify
app = Flask(__name__)
products = [
{"id": 1, "name": "Apple", "price": 1.0},
{"id": 2, "name": "Banana", "price": 0.5},
]
cart = {}
@app.route('/products', methods=['GET'])
def get_products():
return jsonify(products)
@app.route('/cart', methods=['POST'])
def add_to_cart():
product_id = request.json.get('productId')
quantity = request.json.get('quantity', 1)
if product_id not in cart:
cart[product_id] = 0
cart[product_id] += quantity
return jsonify(cart)
if __name__ == '__main__':
app.run(debug=True)
JavaScript (Node.js with Express) 后端示例
javascript
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
let products = [
{ id: 1, name: 'Apple', price: 1.0 },
{ id: 2, name: 'Banana', price: 0.5 }
];
let cart = {};
app.get('/products', (req, res) => {
res.json(products);
});
app.post('/cart', (req, res) => {
const { productId, quantity = 1 } = req.body;
if (!(productId in cart)) {
cart[productId] = 0;
}
cart[productId] += quantity;
res.json(cart);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
前端示例 (HTML/CSS/JavaScript with jQuery)
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Shopping Cart</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Products</h1>
<ul id="product-list"></ul>
<h2>Cart</h2>
<ul id="cart-list"></ul>
<script>
$(document).ready(function() {
function loadProducts() {
$.ajax({
url: '/products',
type: 'GET',
success: function(data) {
$('#product-list').empty();
data.forEach(function(product) {
$('#product-list').append(`<li>${product.name} -
$$
{product.price} <button data-id="${product.id}">Add to Cart</button></li>`);
});
}
});
}
#chhas{
margin-top: 50px;
padding:ep31.cn;
font-size: 18px;
cursor: 10px 20px;
}
function loadCart() {
$.ajax({
url: '/cart',
type: 'GET',
success: function(data) {
$('#cart-list').empty();
Object.keys(data).forEach(function(productId) {
const quantity = data[productId];
const product = products.find(p => p.id == productId);
$('#cart-list').append(`<li>${quantity} x ${product.name}</li>`);
});
}
});
}
loadProducts();
$('body').on('click', 'button', function() {
const productId = $(this).data('id');
$.ajax({
url: '/cart',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ productId: productId }),
success: function() {
loadProducts();
loadCart();
}
});
});
});
</script>
</body>
</html>