Flask Web应用中Python列表转下拉菜单及回传选中值问题
Flask下拉菜单实现与错误修复方案
错误原因分析与修复
1. 解决'Uncaught SyntaxError: Unexpected token '{'错误
该错误源于前端JavaScript直接解析未正确转义的Python变量。Python列表的语法(如单引号)在JS中会被视为非法字符,需先将Python列表转换为标准JSON字符串再传递给前端。
2. 解决JSON.parse解析错误
此错误是因为传入的字符串并非有效JSON格式。直接传递Python列表会被Jinja2转义引号,导致JSON解析失败,需使用json.dumps生成标准JSON字符串,并通过|safe过滤器避免转义。
完整实现代码
后端代码(app.py)
from flask import Flask, render_template, request import json app = Flask(__name__) # 下拉菜单数据源 dropdown_options = ["选项A", "选项B", "选项C", "选项D"] @app.route('/') def index(): # 将Python列表转为JSON字符串传递给模板 return render_template('index.html', options=json.dumps(dropdown_options)) @app.route('/submit', methods=['POST']) def handle_submit(): # 获取前端提交的选中值 selected_item = request.form.get('selected_option') # 此处可添加业务逻辑(如存储、计算等) print(f"用户选中:{selected_item}") return f"已接收选中值:{selected_item}" if __name__ == '__main__': app.run(debug=True)
前端代码(templates/index.html)
<!DOCTYPE html> <html> <head> <title>Flask下拉菜单示例</title> </head> <body> <!-- 传统表单提交 --> <form action="/submit" method="POST"> <select name="selected_option" id="dropdown"> <option value="">请选择选项</option> </select> <button type="submit">提交</button> </form> <script> // 解析后端传递的JSON选项列表 const options = JSON.parse('{{ options|safe }}'); const dropdown = document.getElementById('dropdown'); // 动态生成下拉选项 options.forEach(item => { const option = document.createElement('option'); option.value = item; option.textContent = item; dropdown.appendChild(option); }); </script> </body> </html>
可选:AJAX异步提交实现
若需无刷新提交,可替换前端JS代码为以下内容:
document.querySelector('button').addEventListener('click', function(e) { e.preventDefault(); // 阻止默认表单跳转 const selectedValue = document.getElementById('dropdown').value; fetch('/submit', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `selected_option=${encodeURIComponent(selectedValue)}` }) .then(res => res.text()) .then(data => { alert(data); // 显示后端响应结果 }) .catch(err => console.error('提交失败:', err)); });
内容的提问来源于stack exchange,提问作者Subham
相关产品推荐
相关产品推荐

