0

我有一个小型 Flask 应用程序,它处理表单输入并使用 HTMX 在同一页面上显示结果。当页面加载时,默认表单值用于计算结果。这是hx-trigger="load"在表格上完成的。但如果新值输入到表单并提交,则结果不会更新。如果我hx-trigger="load"从表单中删除,一切正常,但在页面首次加载时表单不会被提交。如何在页面加载时使用 HTMX 提交表单以及单击“提交”按钮时提交表单?

烧瓶app.py如下所示。

from flask import Flask
from flask import render_template
from flask import request

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/results', methods=['POST'])
def results():
    values = request.form['values']
    multiplier = request.form['multiplier']

    vals = list(map(int, values.split(', ')))
    mult = int(multiplier)

    y = []
    for val in vals:
        y.append(val * mult)

    return render_template('results.html', results=y)

index.html模板如下所示。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

    <title>Home Page</title>
</head>
<body>
    <div class="container">
        <div class="row">

            <div class="col">
                <h1 class="mt-3">Submit values</h1>

                <p>Input using comma separated values then click the submit button to see results.</p>

                <form hx-post="/results" hx-target="#results" hx-trigger="load">
                    <div class="mb-3">
                        <label for="values" class="form-label">Values</label>
                        <input type="text" class="form-control" style="max-width:200px;" name="values" value="1, 2, 3, 4, 5">
                    </div>
                    <div class="mb-3">
                        <label for="multiplier" class="form-label">Multiplier</label>
                        <input type="text" class="form-control" style="max-width:200px;" name="multiplier" value="3">
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>

            <div class="col">
                <div id="results"></div>
            </div>

        </div>
    </div>

    <script src="https://unpkg.com/htmx.org@1.6.1" integrity="sha384-tvG/2mnCFmGQzYC1Oh3qxQ7CkQ9kMzYjWZSNtrRZygHPDDqottzEJsqS4oUVodhW" crossorigin="anonymous"></script>

</body>
</html>

results.html模板如下所示。

<h1 class="mt-3">Results</h1>

<p>Below are the results using the form inputs.</p>

{{ results }}
4

1 回答 1

1

当您为 HTMX 提供触发事件时,默认的会被替换为它。对于表单元素,默认事件是submit. 幸运的是 HTMX支持多个触发器,我们只需要用逗号分隔它们。因此,只需添加submithx-trigger属性,HTMX 就会再次监听提交事件:

<form hx-post="/results" hx-target="#results" hx-trigger="submit, load">
于 2022-01-29T19:54:15.483 回答