如何使用 Python 将字符串发送到 HTML?

How can I send a string to HTML using Python?

提问人:Kyle_3_1415 提问时间:11/16/2023 最后编辑:Peter MortensenKyle_3_1415 更新时间:11/17/2023 访问量:54

问:

我有通过按钮元素将变量发送到 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>

我尝试了几种方法,但都失败了。

蟒蛇 HTML

评论

0赞 Gabriel Ramuglia 11/16/2023
问题是你试图直接在 HTML 脚本标签中使用 Python 代码,这是不可能的,因为浏览器不执行 Python。相反,您应该使用 Flask 或 Django 等框架设置 Python 后端,并使用 AJAX 将请求从 HTML 页面发送到 Python 服务器,然后 Python 服务器使用要显示的数据进行响应。
1赞 InSync 11/16/2023
Python 无法在客户端运行(无需大量努力)。如果要编写客户端应用,请使用 JS/TS。如果要编写服务器端应用程序,请确保在浏览器和服务器之间来回发送数据。除此之外,这个问题几乎是无法回答的。

答:

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