我正在尝试使用 Python 和 Flask 编写基于文本的 Pokemon 游戏。我希望用户能够通过单击网页上的按钮来选择他们的 Pokemon,这个 user_pokemon_name 变量将被发送到后端,然后使用有关 Pokemon 的各种统计数据更新网页。然后游戏将继续,并显示新按钮和新消息。
我面临的问题是,一旦用户单击按钮,就会在相同的 URL 处加载一个新的 HTML 页面,并在正文中包含响应。
这是我的 app.py 代码:
from flask import Flask, render_template, request
app = Flask(__name__ ,
static_url_path='',
static_folder='../frontend/static',
template_folder='../frontend/templates')
@app.route("/battle")
def battle_page():
return render_template('battle.html')
@app.route("/battle", methods=['POST'])
def get_user_choice():
user_pokemon_name = request.form['userPokemonChoice']
print(user_pokemon_name)
user_choice = f"You have chosen {user_pokemon_name.capitalize()}."
return user_choice
这是我的 battle.html 代码:
<body>
<section id= "userPokemonChoice">
<p>Now, which Pokemon do you want? The three available Pokemon are Bulbasaur, Charmander, and Squirtle.</p>
<form class = "userinput" method ="POST" action="/battle" id = "form">
<button type = "submit" name = "userPokemonChoice" value="bulbasaur" id="choosePokemon" onclick="getUserChoice()">Bulbasaur</button>
<button type = "submit" name = "userPokemonChoice" value="charmander" id="choosePokemon" onclick="getUserChoice()">Charmander</button>
<button type = "submit" name = "userPokemonChoice" value="squirtle" id="choosePokemon" onclick="getUserChoice()">Squirtle</button>
</form>
</section>
<section id="stats"></section>
这是我的 battle.js 代码
// const form = document.getElementById('form')
// form.addEventListener('submit', (e) => {
// e.preventDefault()
//
// })
function getUserChoice() {
const url = 'http://127.0.0.1:5001/battle'
fetch(url)
.then(response => response)
.then(data => {
console.log(data.text);
document.getElementById("stats").innerHTML = data
})
}
当我按原样运行代码时,显示以下屏幕:
如果我取消注释表单事件监听器,我会收到一个 [object Response],我希望看到响应: object Response
任何帮助都将非常感激--我一直为此而烦恼!