【问题标题】:Change List Value Everytime User Cliked The Button (Python-Flask)每次用户单击按钮时更改列表值(Python-Flask)
【发布时间】:2021-09-04 17:33:28
【问题描述】:

我是学习 Python 和 Flask 的新手。 所以,在 route.py 我有一个定义如下的列表:

symptoms = [0 for i in range (27)]

然后我想在每次单击按钮时更改列表值,当用户单击“是”时,它会将 [index] 元素中的列表更改为 1。当用户单击“否”时,它会更改列表[index] 元素为 0。这是我的 html:

<div name="index_ke" value="0" class="u-container-layout u-container-layout-2">

            <input type="submit" name='cek_diagnose' value='0' class="u-border-2 u-border-black u-btn u-button-style u-hover-black u-none u-text-black u-text-hover-white u-btn-1">NO</input>
            <input type="submit" name='cek_diagnose' value='1' class="u-border-2 u-border-black u-btn u-button-style u-hover-black u-none u-text-black u-text-hover-white u-btn-2">YES</input>

所以我有 27 个 div,其中包含 2 个按钮,所有按钮的名称都相同,带有值 0 和 1。然后这是我的 route.py:

symptoms = [0 for i in range (27)]
@app.route('/tests', methods = ['POST'])
def tests():
    return render_template('index.html', scroll='tests')
def change_list():
    if request.method == 'POST':
      index = int(request.form.get("index_ke"))
      symptoms[index] = int(request.form.get("cek_diagnose"))

从变量索引中,我想保存 div 的名称“index_ke”,其值从 0 到 26 以了解索引,并且我想通过按钮携带的值更改 element[index] 中症状的值.它是正确的还是有其他方法?请给我一些建议以及如何检查我的列表值?提前致谢。

【问题讨论】:

  • 如何制作 27 个按钮、jinja2 for 循环或仅使用 html。
  • 手动使用 HTML
  • 我有 27 个 div,每个 div 有 2 个按钮
  • 好的,所以您想要的是,当用户单击按钮时,应该发送一个值,该值应该包含索引和值 1 或 0(打开和关闭),您使用的是表单标签还是 ajax /fetch api 类似于发送数据的东西。
  • 没错!我在 html 中使用表单标签和方法 post。行动=/测试

标签: python list flask button


【解决方案1】:

您可以通过多种方式做到这一点。我将使用 ajax 和 jquery(javascript)。 在 html 中包含 jquery

<script src="https://code.jquery.com/jquery-3.1.0.js" ></script>

html

{% for i in range(27) %}
<button type="button" id="0" value="{{loop.index}}" class="my_btn_class u-border-2 u-border-black u-btn u-button-style u-hover-black u-none u-text-black u-text-hover-white u-btn-1">off</button>
<button type="button" id="1" value="{{loop.index}}" class="my_btn_class u-border-2 u-border-black u-btn u-button-style u-hover-black u-none u-text-black u-text-hover-white u-btn-1">on</button>
{% endfor %}

javascript

$(document).ready(function() {
$(".my_btn_class").submit(function() {
    $.ajax({
        type: "POST",
        url: `${window.location.pathname}`,
        data: {
            index : this.value, // index is key in request.post.get("index")
            cek_diagnose : this.id // same as above request.post.get("cek_diagnose") 
        },
        contentType: "application/json;charset=UTF-8",
        success: function(res) {
            console.log(res);
        },
    });
})
})

蟒蛇

index = int(request.form.get("index"))
symptoms[index] = int(request.form.get("cek_diagnose"))

您返回的内容将记录在浏览器控制台中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    相关资源
    最近更新 更多