简体   繁体   English

如何让html提交按钮在烧瓶中起作用?

[英]How can I make html submit button functional in flask?

I have a Flask application, and in my html template (which is Jinja2) I have a simple form which has only a button: 我有一个Flask应用程序,在我的html模板(这是Jinja2)中,我有一个只有一个按钮的简单表单:

<form name='resetLayoutForm' method='POST'>
    <input type="submit" value="Reset layout" class="submitButton"/> 
</form>

Now, I want to know how can I 'let the Python script know' that the button was clicked? 现在,我想知道如何让Python脚本知道按钮被点击了?

I tried with: 我尝试过:

@app.route('/localhost/some_route', methods = ['POST', 'GET'])
def function():
    .   .    .
    if request.method == 'POST':
        # code
    .   .    .

but this isn't a good solution, because I have some other operations in the code that are using the POST request method, and I don't want #code to be activated when I use these other POST operations. 但这不是一个好的解决方案,因为我在代码中有一些使用POST请求方法的其他操作,并且我不希望在使用这些其他POST操作时激活#code。

Duplicate the form that contains the button and set it's action to a different URL. 复制包含按钮的表单并将其操作设置为其他URL。 Then, when pressed, only that different URL will receive the data. 然后,按下时,只有不同的URL才会收到数据。

Obviously, as others have noted, there are Javascript mechanisms to achieve this but if those are not needed... 显然,正如其他人所指出的那样,有Javascript机制可以实现这一点,但如果不需要那些......

What do you mean by "'let the Python script know' that the button was clicked?" 你是什​​么意思“'让Python脚本知道'按钮被点击了?”

If you don't want to talk to the server and the button click is only for client side, then why not use Javascript ? 如果您不想与服务器通信并且按钮单击仅适用于客户端,那么为什么不使用Javascript? For example, the simplest way would be to use the onclick event : 例如,最简单的方法是使用onclick事件:

<input type="submit" value="Reset layout" class="submitButton" onclick=doSomething() />

where doSomething() is a javascript function you can write doSomething()是一个可以编写的javascript函数

You can check for the input's value attribute with request.form.values() as such: 您可以使用request.form.values()检查input的value属性:

@app.route('/localhost/some_route', methods = ['POST', 'GET'])
def function():
    # code
    if 'Reset_layout' in request.form.values():
        # code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM