如何基于URL参数自动加载Flask+MySQL的HTML表格
解决方案:访问URL时自动加载Flask查询表格
后端代码修改
调整查询逻辑,让GET/POST请求都能执行数据查询,默认加载全部数据,同时保留搜索过滤功能:
@app.route('/search', methods=['GET','POST']) def search(): # 获取搜索关键词,兼容POST表单和GET参数,默认空字符串 classname = request.form.get('book', '') or request.args.get('book', '') # 无关键词或输入all时,加载全部数据并按日期倒序 if not classname or classname.lower() == 'all': cursor.execute("SELECT * from errordata ORDER BY error_date DESC") else: # 用%通配符实现模糊匹配,适配LIKE查询 cursor.execute("SELECT * from errordata where rule_name LIKE %s", (f"%{classname}%",)) # 查询操作无需commit,直接获取结果 data = cursor.fetchall() data1 = len(data) return render_template('search.html', data=data, data1=data1)
核心修改说明:
- 修正参数获取:前端输入框name为
book,对应改用request.form.get/request.args.get获取,避免KeyError - 默认加载全部数据:直接访问URL时(GET请求)自动返回全量数据
- 修复LIKE查询:添加
%通配符实现模糊匹配,原代码是精确匹配逻辑 - 移除冗余操作:查询不需要
conn.commit(),仅增删改需要提交事务
前端代码修改
保留form标签(维持搜索功能),补充表格表头,确保页面加载时默认数据正常渲染:
<form class="errorboard" method="post" action="" style="margin:auto;max-width:600px"> <input type="text" placeholder="Search by Rule-Name" name="book"> <button type="submit">搜索</button> <!-- 添加提交按钮,优化操作体验 --> <div> Total errors- {{data1}} </div> </form> <table> <!-- 补充表头单元格,替换为你的实际列名 --> <tr bgcolor="#000"> <th>错误ID</th> <th>规则名称</th> <th>错误日期</th> <th>列4</th> <th>列5</th> <th>列6</th> <th>列7</th> <th>列8</th> <th>列9</th> </tr> {% for item in data %} <tr> <td> {{item[0]}} </td> <td> {{item[1]}} </td> <td> {{item[2]}} </td> <td> {{item[3]}} </td> <td> {{item[4]}} </td> <td> {{item[5]}} </td> <td> {{item[6]}} </td> <td> {{item[7]}} </td> <td> {{item[8]}} </td> </tr> {% endfor %} </table>
核心修改说明:
- 保留form标签:既支持搜索提交,又不影响页面默认数据渲染
- 添加提交按钮:避免只能通过回车提交,提升用户体验
- 补全表头:原代码只有表头行无单元格,导致表头显示异常
原修改方案失败原因
- table标签不支持
method=POST属性,不符合HTML规范,直接导致页面渲染异常 - 原后端仅在POST请求时处理查询,直接访问URL(GET请求)无数据返回,所以页面空白
内容的提问来源于stack exchange,提问作者Nayan Tindal
相关产品推荐
相关产品推荐

