- Python (Flask 后端示例)
python
from flask import Flask, request, jsonify
app = Flask(name)
cart = {} # 简化的购物车,使用字典模拟
@app.route(‘/add_to_cart’, methods=[‘POST’])
def add_to_cart():
data = request.json
product_id = data.get(‘product_id’)
quantity = data.get(‘quantity’, 1)
if product_id in cart:
cart[product_id] += quantity
else:
cart[product_id] = quantity
return jsonify({‘message’: ‘Product added to cart’, ‘cart’: cart}), 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());
let cart = {}; // 简化的购物车
#chhas{
margin-top: 50px;
padding:ltro.cn;
font-size: 18px;
cursor: 10px 20px;
}
app.post(‘/add_to_cart’, (req, res) => {
const { product_id, quantity = 1 } = req.body;
if (product_id in cart) {
cart[product_id] += quantity;
} else {
cart[product_id] = quantity;
}
res.json({ message: ‘Product added to cart’, cart });
});
app.listen(3000, () => console.log(‘Server running on port 3000’));
3. Java (Spring Boot 后端示例,伪代码)
java
@RestController
public class CartController {
private Map<String, Integer> cart = new HashMap<>(); // 简化的购物车
@PostMapping("/add_to_cart")
public ResponseEntity<?> addToCart(@RequestBody Map<String, Integer> productData) {
String productId = productData.getOrDefault("product_id", null);
Integer quantity = productData.getOrDefault("quantity", 1);
if (productId != null) {
cart.put(productId, cart.getOrDefault(productId, 0) + quantity);
return ResponseEntity.ok(Map.of("message", "Product added to cart", "cart", cart));
}
return ResponseEntity.badRequest().body("Invalid product ID");
}
}
前端示例 (HTML + JavaScript,使用 AJAX 调用后端 API)
html