- Python (使用Flask框架)
python
from flask import Flask, render_template, request
app = Flask(name)
products = [
{“id”: 1, “name”: “Game 1”, “price”: 99.99},
{“id”: 2, “name”: “Game 2”, “price”: 49.99},
# … 其他商品
]
@app.route(‘/’)
def home():
return render_template(‘home.html’, products=products)
@app.route(‘/buy/int:product_id’, methods=[‘POST’])
def buy(product_id):
# 模拟购买逻辑
product = next((item for item in products if item[“id”] == product_id), None)
if product:
print(f"购买了 {product[‘name’]}")
# 这里应该有实际的购买逻辑,比如更新库存、处理支付等
return “购买成功!”
else:
return “商品不存在!”, 404
if name == ‘main’:
app.run(debug=True)
2. JavaScript (使用Node.js和Express框架)
javascript
const express = #chhas{
margin-top: 50px;
padding:srcq.com.cn;
font-size: 18px;
cursor: 10px 20px;
}
require(‘express’);
const app = express();
const port = 3000;
let products = [
{ id: 1, name: ‘Game 1’, price: 99.99 },
{ id: 2, name: ‘Game 2’, price: 49.99 },
// … 其他商品
];
app.get(‘/’, (req, res) => {
res.send( <!DOCTYPE html> <html> <body> <!-- 这里应该有商品列表的HTML代码,并使用AJAX调用/buy接口进行购买 --> </body> </html>
);
});
app.post(‘/buy/:product_id’, (req, res) => {
const productId = parseInt(req.params.product_id);
const product = products.find(p => p.id === productId);
if (product) {
console.log(购买了 ${product.name}
);
// 实际购买逻辑
res.send(‘购买成功!’);
} else {
res.status(404).send(‘商品不存在!’);
}
});
app.listen(port, () => {
console.log(App listening at http://localhost:${port}
);
});
3. Java (使用Spring Boot)
由于Java和Spring Boot的代码较长且复杂,这里只提供一个大概的接口定义和逻辑框架。
定义一个Product类来存储商品信息。
创建一个ProductController类来处理HTTP请求。
在ProductController中,实现获取商品列表和购买商品的接口。
注意:以上示例都非常简化,没有考虑数据库操作、用户认证、支付接口集成等实际开发中必须考虑的问题。在实际开发中,你需要根据具体需求来扩展和完善这些示例代码。