如何在Flask服务器中获取AJAX请求的下拉框选中参数?
Flask后端无法获取下拉框选中值的解决方案
问题背景
后端能接收到POST请求,但无法获取下拉框cars的选中值,尝试多种request用法均无效。期望在不刷新页面的前提下获取用户选中的车辆值(之前用表单提交可实现,但会刷新页面)。
现有代码
Flask后端代码
import ssl from flask import Flask, redirect, url_for, render_template, jsonify, request from flask_dance.contrib.facebook import make_facebook_blueprint, facebook from flask_dance.contrib.google import make_google_blueprint, google app = Flask(__name__, static_folder='app', static_url_path="/app") app.secret_key = "secret" # 替换为你自己的密钥 @app.route('/appoint', methods=['GET', 'POST']) def appoint(name='appoint'): if request.method == 'POST': data = request.get_data(as_text=True) print(data) return render_template("appoint.html") if __name__ == '__main__': context = ssl.SSLContext() context.load_cert_chain('/etc/letsencrypt/live/annastudio.beauty/fullchain.pem', '/etc/letsencrypt/live/annastudio.beauty/privkey.pem') app.run(host="0.0.0.0", port=443, ssl_context=context)
前端页面及AJAX代码
<html> <head> </head> <body> <label for="cars">Choose a car:</label> <select id="cars"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="opel">Opel</option> <option value="audi">Audi</option> </select> <br><br> <input type="submit" value="Submit" onclick="loadDoc()"> <script> function loadDoc() { const xhttp = new XMLHttpRequest(); xhttp.onload = function() { document.getElementById("cars").innerHTML = this.responseText; } xhttp.open("POST", "https://www.annastudio.beauty/appoint", true); xhttp.send(); } </script> </body> </html>
尝试过程
修改AJAX代码后,后端能接收到下拉框的所有选项HTML内容,但无法获取仅选中的值。尝试通过document.getElementById("cars").value获取选中值,但尚未正确对接后端解析逻辑。
正确解决方案
1. 修改前端AJAX代码(发送选中值)
有两种常见的发送格式可选:
方式一:使用FormData(推荐,无需手动设置请求头)
<script> function loadDoc() { const xhttp = new XMLHttpRequest(); const selectEl = document.getElementById("cars"); const selectedCar = selectEl.value; // 创建FormData对象并添加参数 const formData = new FormData(); formData.append("selected_car", selectedCar); xhttp.open("POST", "/appoint", true); xhttp.send(formData); } </script>
方式二:使用URL编码格式(需手动设置请求头)
<script> function loadDoc() { const xhttp = new XMLHttpRequest(); const selectEl = document.getElementById("cars"); const selectedCar = selectEl.value; xhttp.open("POST", "/appoint", true); // 设置请求头为表单编码格式 xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // 编码参数后发送 xhttp.send(`selected_car=${encodeURIComponent(selectedCar)}`); } </script>
2. 修改Flask后端代码(解析选中值)
对应前端的发送格式,使用request.form获取参数:
@app.route('/appoint', methods=['GET', 'POST']) def appoint(name='appoint'): if request.method == 'POST': # 获取前端发送的选中值 selected_car = request.form.get("selected_car") print("用户选中的车辆:", selected_car) # 这里可以添加后续业务逻辑,比如存入数据库等 return render_template("appoint.html")
问题说明
- 原AJAX代码未发送任何数据,后端自然无法获取值
- 后续错误发送了下拉框的
innerHTML(所有选项的HTML代码),而非选中值 - 通过
selectElement.value可直接获取下拉框的选中值,再通过标准表单格式发送,后端即可用request.form解析
内容的提问来源于stack exchange,提问作者Alex Montsarj
相关产品推荐
相关产品推荐

