如何通过 ajax 脚本将数据从 html 传回 python 文件,以便在同一页面上呈现更多数据
How to pass data from html back to python file through an ajax script in order to render more data on the same page
这是一道 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>
您的 select 没有 ID 只有名称。所以你的 jquery 使用 id
即 #
是不正确的。将 id="id_options"
添加到您的 select
元素。
要获得 selected 值,
model_id = document.getElementById("id_options").value;
或
model_id = $("#id_options").find("option:selected").val();
- 在您的 Ajax 代码中,您没有提交表单,这意味着您不能使用
request.form
。而是尝试 request.values.get("model_id", None)
这是一道 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>
您的 select 没有 ID 只有名称。所以你的 jquery 使用
id
即#
是不正确的。将id="id_options"
添加到您的select
元素。要获得 selected 值,
model_id = document.getElementById("id_options").value;
或
model_id = $("#id_options").find("option:selected").val();
- 在您的 Ajax 代码中,您没有提交表单,这意味着您不能使用
request.form
。而是尝试request.values.get("model_id", None)