- 后端(Python Flask)henanhuahan.com
首先,你需要安装Flask。如果你还没有安装,可以通过pip安装:
bash
pip install flask
然后,创建一个简单的Flask应用来处理游戏商品的展示:
python
app.py
from flask import Flask, jsonify, request
app = Flask(name)
假设的游戏商品列表
games = [
{“id”: 1, “name”: “Cyberpunk 2077”, “price”: 59.99},
{“id”: 2, “name”: “The Witcher 3”, “price”: 39.99},
{“id”: 3, “name”: “Minecraft”, “price”: 26.95}
]
@app.route(‘/’)
def index():
return “Welcome to the Game Store!”
@app.route(‘/games’)
def get_games():
return jsonify(games)
if name == ‘main’:
app.run(debug=True)
2. 前端(HTML + JavaScript)
接下来,创建一个简单的HTML页面来显示这些游戏,并使用JavaScript从后端API获取数据:
html
Welcome to Our Game Store!
<script>
document.addEventListener("DOMContentLoaded", function() {
fetch('/games')
.then(response => response.json())
.then(data => {
const list = document.getElementById('gamesList');
data.forEach(game => {
const item = document.createElement('li');
item.textContent = `${game.name} -
$$
{game.price}`;
list.appendChild(item);
});
})
.catch(error => console.error(‘Error:’, error));
});
- 后端(Python Flask)
首先,你需要安装Flask。如果你还没有安装,可以通过pip安装:
bash
pip install flask
然后,创建一个简单的Flask应用来处理游戏商品的展示:
python
app.py
from flask import Flask, jsonify, request
app = Flask(name)
假设的游戏商品列表
games = [
{“id”: 1, “name”: “Cyberpunk 2077”, “price”: 59.99},
{“id”: 2, “name”: “The Witcher 3”, “price”: 39.99},
{“id”: 3, “name”: “Minecraft”, “price”: 26.95}
]
@app.route(‘/’)
def index():
return “Welcome to the Game Store!”
@app.route(‘/games’)
def get_games():
return jsonify(games)
if name == ‘main’:
app.run(debug=True)
2. 前端(HTML + JavaScript)
接下来,创建一个简单的HTML页面来显示这些游戏,并使用JavaScript从后端API获取数据:
html
Welcome to Our Game Store!
<script>
document.addEventListener("DOMContentLoaded", function() {
fetch('/games')
.then(response => response.json())
.then(data => {
const list = document.getElementById('gamesList');
data.forEach(game => {
const item = document.createElement('li');
item.textContent = `${game.name} -
$$
{game.price}`;
list.appendChild(item);
});
})
.catch(error => console.error(‘Error:’, error));
});