如何通过HTML向Flask后端发送GET请求获取指定员工数据?
解决方案:用HTML表单发送带路径参数的GET请求到Flask后端
问题根源
HTML的<form>标签使用GET方法时,会自动将表单字段以**查询字符串(?key=value)**的形式附加到action指定的URL后,而非替换路径中的占位符(比如<name>)。直接写action="/employee/<name>"无效,因为浏览器不会解析并替换这个占位符。
解决方案1:用JavaScript动态构造路径(匹配你的路径参数需求)
通过监听表单提交事件,动态将输入的用户名拼接到目标路径中,再发送GET请求。
完整Flask+MongoDB后端代码
from flask import Flask, render_template_string, jsonify from pymongo import MongoClient app = Flask(__name__) # 连接本地MongoDB(默认端口),指定数据库和集合 client = MongoClient('mongodb://localhost:27017/') db = client['employee_db'] employees_collection = db['employees'] # 根路由返回带表单的HTML页面 @app.route('/') def index(): return render_template_string(''' <!DOCTYPE html> <html> <head> <title>员工信息查询</title> </head> <body> <h3>输入姓名查询员工信息</h3> <form id="queryForm"> <input type="text" id="nameInput" placeholder="请输入姓名" required> <button type="submit">查询</button> </form> <div id="resultArea"></div> <script> const form = document.getElementById('queryForm'); const resultArea = document.getElementById('resultArea'); form.addEventListener('submit', function(e) { e.preventDefault(); // 阻止默认的表单提交行为 const userName = document.getElementById('nameInput').value.trim(); if (userName) { // 构造带路径参数的URL,用encodeURIComponent处理特殊字符(如空格、中文) const targetUrl = `/employee/${encodeURIComponent(userName)}`; // 发送GET请求并处理响应 fetch(targetUrl) .then(res => { if (!res.ok) throw new Error('未找到该员工'); return res.json(); }) .then(data => { resultArea.innerHTML = ` <h4>查询结果:</h4> <p>姓名:${data.name}</p> <p>职位:${data.position || '未填写'}</p> <p>部门:${data.department || '未填写'}</p> `; }) .catch(err => { resultArea.innerHTML = `<p style="color:red;">${err.message}</p>`; }); } }); </script> </body> </html> ''') # 处理带路径参数的GET请求 @app.route('/employee/<name>') def get_employee(name): # 从MongoDB查询数据,排除_id字段避免JSON序列化问题 employee = employees_collection.find_one({'name': name}, {'_id': 0}) if employee: return jsonify(employee) else: return jsonify({'error': '员工不存在'}), 404 if __name__ == '__main__': app.run(debug=True)
关键说明
- 用
encodeURIComponent处理用户名中的特殊字符,避免URL解析错误 - 通过
fetch发送请求并在页面上展示结果,无需跳转页面 - MongoDB查询时排除
_id字段,确保返回的JSON可以正常序列化
解决方案2:改用查询字符串参数(无需JavaScript)
如果可以接受URL格式为/employee?name=xxx,则直接用原生表单即可实现:
修改后的Flask路由
@app.route('/employee') def get_employee(): name = request.args.get('name') if not name: return jsonify({'error': '请提供姓名参数'}), 400 # 查询MongoDB employee = employees_collection.find_one({'name': name.strip()}, {'_id': 0}) if employee: return jsonify(employee) else: return jsonify({'error': '员工不存在'}), 404
简化后的HTML表单
<form action="/employee" method="GET"> <input type="text" name="name" placeholder="请输入姓名" required> <button type="submit">查询</button> </form>
关键说明
- 表单的
method="GET"会自动将name字段的值拼接到URL的查询字符串中 - Flask通过
request.args.get('name')获取参数值 - 这种方式无需JS,适合简单场景,但URL格式与你原本的需求略有差异
内容的提问来源于stack exchange,提问作者הינדה הרשטיק
相关产品推荐
相关产品推荐

