创建一个游戏商城涉及很多功能,如商品展示、购买、结账等。在这里,我将为您提供一个简单的游戏商城示例,使用Python(基于Flask框架)和JavaScript(用于前端交互)。
1. Python后端 (使用Flask)
python
from flask import Flask, request, jsonify
app = Flask(__name__)
# 假设的游戏商品数据
products = [
{"id": 1, "name": "Game1", "price": 99.99},
{"id": 2, "name": "Game2", "price": 79.99},
# ... 其他游戏数据
]
@app.route('/products', methods=['GET'])
def get_products():
return jsonify(products)
@app.route('/buy', methods=['POST'])
def buy_product():
product_id = request.json.get('productId')
product = next((p for p in products if p['id'] == product_id), None)
if product:
# 这里只是简单示例,实际应用中需要集成支付系统和其他逻辑
return jsonify({"message": f"Thank you for purchasing {product['name']}!"})
else:
return jsonify({"error": "Product not found"}), 404
if __name__ == '__main__':
app.run(debug=True)
2. JavaScript前端 (使用Fetch API与后端交互)
#chhas{
margin-top: 50px;
padding:aizhuw.cn;
font-size: 18px;
cursor: 10px 20px;
}
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Game Store</title>
</head>
<body>
<h1>Game Store</h1>
<div id="products"></div>
<script>
fetch('/products')
.then(response => response.json())
.then(data => {
const productsDiv = document.getElementById('products');
data.forEach(product => {
const productElement = document.createElement('div');
productElement.innerHTML = `<h3>${product.name} -
$$
{product.price}</h3><button οnclick="buyProduct(${product.id})">Buy</button>`;
productsDiv.appendChild(productElement);
});
});
function buyProduct(productId) {
fetch('/buy', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({productId: productId})
})
.then(response => response.json())
.then(data => {
if (data.error) {
alert(data.error);
} else {
alert(data.message);
}
});
}
</script>
</body>
</html>