提问人:Kyle_3_1415 提问时间:11/16/2023 最后编辑:Peter MortensenKyle_3_1415 更新时间:11/17/2023 访问量:54
如何使用 Python 将字符串发送到 HTML?
How can I send a string to HTML using Python?
问:
我有通过按钮元素将变量发送到 Python 的 HTML 代码。我希望 Python 将字符串发送回 HTML,并且 HTML 将其显示在页面上,就像在 <p> 标签中一样。
<!DOCTYPE html>
<html>
<head>
<title>PythonGame.html</title>
<script type="python">
# objectGame.py
import numpy
def test_view(requests):
if(request.method == 'POST' && request.POST['attack'] == 'attack'):
# do what you want when button clicked
else:
# other things in your views if you have
return render(requests, '1st.html', {})
</script>
</head>
<body>
<table border="1">
<tr>
<th><form action="" method="post"><button class="btn" type="submit" name="attack" value="attack">attack/pickup</button></form></th>
<th><form action="" method="post"><button class="btn" type="submit" name="forward" value="forward"> forward </button></form></th>
<th><form action="" method="post"><button class="btn" type="submit" name="run" value="run"> run </button></form></th>
</tr>
<tr>
<th><form action="" method="post"><button class="btn" type="submit" name="left" value="left"> left </button></form></th>
<th><form action="" method="post"><button class="btn" type="submit" name="backward" value="backward"> backward </button></form></th>
<th><form action="" method="post"><button class="btn" type="submit" name="right" value="right"> right </button></form></th>
</tr>
</table>
</body>
</html>
我尝试了几种方法,但都失败了。
答:
0赞
Marco Parola
11/16/2023
#1
您可以使用 Ajax 将请求从 HTML 页面发送到 Python 服务器(Flask 非常常见)。安装 Flask 后,请尝试以下操作 ():pip install Flask
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
@app.route('/')
def index():
return render_template('1st.html')
@app.route('/process', methods=['POST'])
def process():
if request.method == 'POST':
value = request.form['attack'] # Get the value of the 'attack' button
response_data = "Attack button clicked: {}".format(value) # Example: sending a response back to the HTML
return jsonify({'response': response_data})
if __name__ == '__main__':
app.run(debug=True)
最后,运行服务器。
python app.py
然后进入您的浏览器。http://localhost:5000
评论