You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Flask中HTML Select标签异常行为技术求助

Fixing the Unexpected <select> Behavior in Your Flask Template

我一眼就看出问题出在哪啦——你把<select>标签放进了Flask模板的for循环里,这会导致每一条location数据都生成一个独立的下拉框,而不是一个包含所有选项的单一选择器,这就是你看到的“奇怪现象”的根源。

修正后的前端代码

把<select>标签移到循环外面,只让option标签循环生成,这样就能得到一个正常的下拉选择框:

HTML with data-binding Location:<br>
<select name="location">
    {% for item in data %}
        <option value="{{ item[0] }}">{{ item[0] }}</option>
    {% endfor %}
</select>

后端代码优化(可选)

如果你的location表只有一个存储地点名称的字段,当前代码没问题,但可以优化得更清晰——明确指定查询字段,避免后续用索引取值:

@app.route('/events', methods = ['POST', 'GET'])
def events():
    cursor = conn.cursor()
    # 明确查询地点字段,替换成你实际的字段名
    cursor.execute('SELECT location_name FROM location')
    rows = cursor.fetchall()
    # 直接提取每个元组的第一个元素,得到纯地点列表
    data = [row[0] for row in rows]
    cursor.close()
    return render_template('events.html', data = data)

对应的前端就可以简化成:

<option value="{{ item }}">{{ item }}</option>

额外小提示

  • 表单提交后,后端可以用request.form.get('location')获取用户选中的地点值
  • 如果需要设置默认选中项,只要给对应的option加selected属性就行:
    <option value="{{ item }}" {% if item == "默认地点" %}selected{% endif %}>{{ item }}</option>
    

内容的提问来源于stack exchange,提问作者Dawn17

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:47:12