简体   繁体   English

如何在 Python/flask 中读取 HTML 复选框的状态

[英]How to read the state of an HTML checkbox in Python / flask

I've built a working web page and python/flask program but cannot figure out how to read the state of a webpage checkbox in the python code.我已经构建了一个工作网页和 python/flask 程序,但无法弄清楚如何在 python 代码中读取网页复选框的状态。 I've figured out how to set a checkbox from python, just not how to read it.我已经想出了如何从 python设置复选框,而不是如何阅读它。 Here is the html for one of the checkboxes:这是其中一个复选框的 html:

<div class="slideThree">    
    <input type="checkbox" value="None" id="chk_01" name="chk_01" {{chk_01_checked}}/>
    <label for="chk_01"></label>
</div>

The html code is in a separate file from the python program. html 代码位于与 python 程序不同的文件中。 It looks like I need to use some combination of 'request' or 'get' instructions but cannot find clear examples on how to do it.看起来我需要使用“请求”或“获取”指令的某种组合,但找不到有关如何执行此操作的明确示例。 I'm a novice in both python and html, so any help appreciated.我是 python 和 html 的新手,所以感谢任何帮助。

The checkbox exists in the browser, the python code runs on the server.该复选框存在于浏览器中,python 代码在服务器上运行。 Basically the server will have no knowlegde of the checkbox state.基本上服务器不会知道复选框状态。 If you want to change that, you need to connect the two.如果你想改变它,你需要将两者联系起来。

Two options there:有两个选项:

(1): the checkbox is included in a form and the state is included in the form data when the user clicks submit. (1):复选框包含在表单中,状态包含在用户点击提交时的表单数据中。

(2): you assign an event handler to the state of the checkbox. (2):您为复选框的状态分配一个事件处理程序。 On the event handler, you post the new state to some AJAX resource.在事件处理程序上,您将新状态发布到某个 AJAX 资源。 In Flask you add a route for the AJAX URL and receive the state changes.在 Flask 中,您为 AJAX URL 添加路由并接收状态更改。

Here is what I am trying to do.这就是我想要做的。 I added a action (form action) line in html, then a function in python to process it.我在html中添加了一个动作(表单动作)行,然后在python中添加了一个函数来处理它。 But the python function never executes so I clearly don't have something right.但是 python 函数永远不会执行,所以我显然没有正确的东西。

here is the html:这是html:

<td style="width:auto">
<form action="ManToggle">
<div class="slideThree">
    <input type="checkbox" value="None" id="chk_01_Man" name="chk_01_Man" />
    <label for="chk_01_Man"></label>
</div>
</form>
</td> 

Here is the python:这是蟒蛇:

@app.route('/ManToggle', methods=['GET'])
def ManToggleUpdate():
    print ("function executes")
    test = request.form['chk_01_Man']
    if test == True :
        # do something
    else :
        # do something else

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

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