我想将javascript变量传递到jinja2 url_for构造中。但是它似乎只读取纯字符串,而不读取变量。可以做到吗?我的脚本在HTML文件中。在下面的代码中,我希望name参数等于变量文本,但是它只是不解析它。
<script>
function process_search_submit() {
if (chosenId === "") {
alert("Please choose a category");
} else {
var text = $("#media_name").val();
if (text === "") {
alert("Please enter a name of anime/manga/book you want to search");
} else {
var category = chosenId;
if (category === "anime") {
$('#query_form').attr("action", "{{url_for('anime', name=text)}}");
} else if (category === "manga") {
$('#query_form').attr("action", `{{url_for('manga', name=text)}}`);
}
$('#query_form').submit();
}
}
}
</script>
更新,来自views.py
@app.route("/anime", methods=["POST"])
def anime():
name = request.args["name"]
我只想在URL中使用/anime/{user typed name of anime}
或/anime?name={user typed name of anime}
动画。
答案 0 :(得分:0)
应该可以。将这些添加到您的模板中以进行诊断:
{{ text }}
{{ url_for('anime', name=text) }}
并查看实际插入到模板中的内容。 S
您的视图应类似于:
@app.route("/anime/<text>", methods=["GET", "POST"])
def anime(text=""):
return render_template('hello.html', text=text)