选择下拉菜单后,选定的值在flask中未显示?

4

如何使用已由flask - render_template预填充的HTML <select>下拉列表。

这是一个已由Flask-Jinja2预填充的<select>下拉列表。

<div>
    <select class="test-default" id="testTime">
        {% for option in options %}
        <option value={{ option }}>{{ option }}</option>
        {% endfor %}
    </select>
</div>

test.html文件中的脚本。

function fetch_test_data(){
    let test = $("#testTime").val();
    axios({ 
        method:"get",
        url:"/test",
        params: {
            test
        }
    }).then(function (response) {
        $(document.body).html(response.data)
    }); 
}

有一个 test.py 文件 - 包含应用程序路径和下拉菜单的 options

@app.route('/test', methods=["GET"])
@login_required
def transactions_view():
    options = ["0","7","14","30"]

    return render_template("test.html", options=options)

在上述情况下如何使用selected属性来显示所选的值。
当选择一个值时,正确的值将被返回到Flask并呈现回来。但是下拉可视化/列表显示的是第一个值而不是选定的值?
我尝试过:
我能够获取定义的下拉列表的dropdownselect参考为defined-dropdown
<div>
    <select class="test-default" id="testTime">
    <option value=0>today</option>
    <option value=7>week</option>
    <option value=14>fortnight</option>
    <option value=30>month</option>
    </select>
</div>

{{ time }}

我能够使用上述下拉菜单来完成以下操作:

<div>
    <select class="test-default" id="testTime">
    <option value=0 {% if time == 0 %} selected="selected" {% endif %}>today</option>
    <option value=7 {% if time == 7 %} selected="selected" {% endif %}>week</option>
    <option value=14 {% if time == 14 %} selected="selected" {% endif %}>fortnight</option>
    <option value=30 {% if time == 30 %} selected="selected" {% endif %}>month</option>
    </select>
</div>

其中{{ time }}是从test.py返回的时间。

@app.route('/test', methods=["GET"])
@login_required
def transactions_view():
    time = (request.args.get("test"))
    return render_template("test.html", time=time)

将您的变量值解析为整数,例如:int(time) - udit rawat
@Zanthoxylum-piperitum 为什么您会在一个问题上添加赏金,然后又放弃它呢? - Dauros
3个回答

0

在我看来,我们应该避免让我们的 HTML/渲染逻辑泄漏到我们的路由/控制器处理程序中。因此,对于上面的示例,您应该仅对模板 HTML 进行更改。最后,我认为 JavaScript 是一种更好、更清晰的实现方式,而不是使用 Jinja 条件语句。

<!--  /templates/time.html -->
{% 
   set time_lookup = { 
        0:  "Today",
        7:  "Week",
        14: "Fortnight",
        30: "Month",
    }
%}
<div>
    <select class="test-default" id="testTime">
        {% for option in options %}
           <option value={{ option }}>{{ time_lookup[option] }}</option>
        {% endfor %}
    </select>
</div>
<script>

const urlParams = new URLSearchParams(window.location.search); 
// current url and parse our query params "?test=201"

const timeParam = urlParams.get("time") || "0";
// default to 0

const option = document.querySelector("select.test-time option[value=" + timeParam + "]") 
// returns <option> HTMLElement where value === timeParam

option.setAttribute("selected", true)
// set <option selected="true"> on HTMLElement

</script>

0

您需要在transactions_view()中传递所选时间至模板,并在渲染过程中测试每个选项的值。

首先,在test.py文件中,您需要像这样修改transactions_view():

@app.route('/test', methods=["GET"])
@login_required
def transactions_view():
    options = (
        (0, 'today'),
        (7, 'week'),
        (14, 'fortnight'),
        (30, 'month'),
    )
    default_time = 0
    selected_time = int(request.args.get('time', default_time))

    return render_template("test.html", options=options, selected_time=selected_time)

在这里,我们有一个options变量作为键-标签对的元组,selected_time变量保存从GET请求中选择的时间的值或默认值。这两个变量都已传递给render_template函数,因此我们可以在模板文件中访问它们。

test.html模板文件中,您需要像这样修改for循环:

<div>
  <select class="test-default" id="testTime">
    {% for time, label in options %}
    <option value="{{ time }}" {% if time == selected_time %}selected="selected"{% endif %}>{{ label }}</option>
    {% endfor %}
  </select>
</div>

这里我们测试每个选项的time值是否为所选时间,并相应设置selected属性。


-1

axios使用更新的时间参数获取响应,但是您需要加载响应(即更新后的HTML)才能查看更新后的时间。

您可以按照下面所示的方式更新fetch_test_data函数,以在下拉值更改时加载HTML响应。

function fetch_test_data(){
    let test = $("#testTime").val();
    axios({ 
        method:"get",
        url:"/test",
        params: {
            test
        }
    }).then(function (response) {
        $(document.body).html(response.data)
    }); 
}

如果您不需要使用axios,只是想更新时间,以下代码将可以实现此功能,而无需发送请求。
<span id=timelabel>Default Time</span>


<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>

    var label = document.getElementById('timelabel');
    var dropdown = document.getElementById('testTime');

    $("#testTime").on("change",function (evt) {
        label.textContent = dropdown.value;
    })
</script>

请提供更新后的问题,谢谢。 - user11509999

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接