- Python (使用Flask框架)
gzjiazheng.cn
python
from flask import Flask, render_template, request
app = Flask(name)
假设的商品列表
products = [
{“id”: 1, “name”: “产品A”, “price”: 100},
# … 更多商品
]
@app.route(‘/’)
def index():
return render_template(‘index.html’, products=products)
@app.route(‘/cart’, methods=[‘POST’])
def cart():
# 简化处理,只添加第一个商品到购物车(实际中需要更复杂的逻辑)
product_id = request.form.get(‘product_id’)
product = next((p for p in products if p[‘id’] == int(product_id)), None)
if product:
# 这里只是打印,实际中你可能需要将购物车数据保存到数据库或session中
print(f"Added {product[‘name’]} to cart.")
return “Product added to cart.”, 200
else:
return “Product not found.”, 404
if name == ‘main’:
app.run(debug=True)
2. JavaScript (Node.js 使用Express框架)
javascript
const express = require(‘express’);
const app = express();
const bodyParser = require(‘body-parser’);
app.use(bodyParser.urlencoded({ extended: false }));
// 假设的商品列表
const product