【发布时间】:2021-11-24 15:11:10
【问题描述】:
这是一个 Flask 问题。
我有一个下拉菜单和一个按钮。我希望按下按钮并将下拉列表的当前值发送回 python 函数。这个 python 函数会做一些事情并确定页面的进一步内容。
如果我重定向到一个新页面,我不需要使用任何 ajax 并且选择的值会很好地传递回 python 函数。
如果我不重定向而是尝试在同一页面上呈现所选值(这是我的要求),据我从本网站上的其他帖子中可以看出,我必须使用 Ajax 来调用 python 函数,但它没有捕获选定的值。
还请注意页面不应重新呈现的限制。
我真的很茫然,因为我不明白这两种情况之间的区别。任何帮助将非常感激。我对 python 有很好的经验,但是 Flask 和 html 对我来说非常新。
见下面的代码:
setup.py:
from app import app
# Data for initialisation of setup page
@app.route("/setup", methods=["GET", "POST"])
def create_models_dropdown():
# Gets used to create the dropdown
model_ids = list(range(1, 11))
return render_template ("setup.html", ids=model_ids)
# Further data to be added on button click
@app.route('/test', methods=["GET", "POST"])
def test():
###
# Debugging
print(request.form)
# When redirecting to a new page, this gives ImmutableMultiDict([('id_options', '5')]) (or whatever value is selected)
# So the data is being returned
# When staying on the same page (using the ajax script), this gives ImmutableMultiDict([]) so the dropdown value is not being returned
###
model_id = request.form.get("id_options") # succeeds/fails as per comments above
# Do something with the model_id
return jsonify(result=(model_id or -1) * 2)
setup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta charset="UTF-8" />
<title>Wut</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
var $SCRIPT_ROOT = "";
</script>
</head>
<body>
<!--
action="{{ url_for('test') }}" will render the new page and work as expected
if i take it out, the result of running the script below will instead render
-->
<form action="{{ url_for('test') }}" method="post">
<select name="id_options" width="300px">
{% for id in ids %}
<option value="{{ id }}" SELECTED>{{ id }}</option>
{% endfor %}
</select>
<button class="get_result" type="button">Same page</button>
<button class="get_result">New page</button>
</form>
<div class="result"></div>
</body>
<script>
// This works in the sense that it calls the function
$(document).on('click', '.get_result', function () {
// Debugging
// This was another attempt to get the value from the dropdown and pass it back which also didn't work
// var model_id = $("#id_options").val();
// console.log(model_id)
//
$.ajax({
url: "/test",
type: "get",
// data: { model_id: model_id },
success: function (response) {
$(".result").html('<h1>' + response.result.toString() + '</h1>');
},
});
});
</script>
</html>
【问题讨论】: