创建一个完整的购物商城代码是一个庞大且复杂的任务,涉及前端、后端、数据库、支付接口等多个方面。我可以为您提供一些简单的示例或框架,以帮助您开始构建自己的购物商城。以下是使用几种不同技术栈的示例代码:
1. Python (Flask框架) 后端示例
python
from flask import Flask, request, jsonify
app = Flask(__name__)
# 假设的商品数据
products = [
{"id": 1, "name": "Product 1", "price": 100},
{"id": 2, "name": "Product 2", "price": 200},
]
@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)
# 这里可以添加购物车逻辑,比如将商品添加到数据库等
return jsonify({"message": f"Product {product_id} added to cart with quantity {quantity}"}), 200
if __name__ == '__main__':
app.run(debug=True)
2. JavaScript (Node.js 和 Express框架) 后端示例
javascript
const express = require('express');
const app = express();
app.use(express.json());
// 假设的商品数据
const products = [
{id: 1, name: 'Product 1', price: 100},
{id: 2, name: 'Product 2', price: 200},
];
app.get('/products', (req, res) => {
res.json(products);
});
#chhas{
margin-top: 50px;
padding:gwygov.cn;
font-size: 18px;
cursor: 10px 20px;
}
app.post('/cart', (req, res) => {
const { productId, quantity = 1 } = req.body;
// 这里可以添加购物车逻辑
res.json({ message: `Product ${productId} added to cart with quantity ${quantity}` });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
3. 前端HTML和JavaScript示例 (使用Fetch API与后端通信)
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Shopping Cart</title>
</head>
<body>
<h1>Products</h1>
<ul id="products"></ul>
<button id="addToCartBtn">Add to Cart</button>
<script>
fetch('/products')
.then(response => response.json())
.then(data => {
const productsList = document.getElementById('products');
data.forEach(product => {
const li = document.createElement('li');
li.textContent = `${product.name} -
$$
{product.price}`;
li.dataset.id = product.id;
productsList.appendChild(li);
});
});
document.getElementById('addToCartBtn').addEventListener('click', function() {
const selectedProductId = document.querySelector('#products li.selected').dataset.id;
fetch('/cart', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ productId: selectedProductId })
}).then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Network response was not ok.');
}).then(data => {
console.log(data.message);
}).catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
});
</script>
</body>
</html>