为此经历了一段艰难的时光。我通过 Ajax 将一些数据发送到正在处理数据的 Flask 服务器路由,希望随后使用处理后的数据渲染一个新模板。数据似乎从我的 Javascript 良好地流向我的 Flask 服务器。 (我正在使用 JSGlue for Flask.url_for。)但是一旦它到达“return render_template”,它就会死掉。我没有收到回溯错误或任何东西。我已经尝试过 print() 和 console.log 来了解是什么杀死了它,但到目前为止我还是一无所获。我是否遗漏了一些明显的东西?
mypage.js
let c_list = [1,2,3....];
$.ajax({
url: Flask.url_for('get_genres'),
type: "POST",
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(c_list),
success: function (data) {
console.log(data);
}
})
init.py
@app.route('/get_genres', methods=["GET", "POST"]
def get_genres():
if request.method == "POST":
categories = request.json
c = Querybuilder()
genres = c.genres_from_c(categories)
return render_template("genres.html", genres=genres)
index.html
<head>
{{ JSGlue.include() }}
</head>
<body>
{% block body %}
{% endblock %}
</body>
流派.html
{% extends "index.html" %}
{% block body %}
<div class="genre_list">
{% for genre in genres %}
<a href="#" src="{{ genres[genre] }}" class="unclicked" onclick="toggleClicked(this)">
<p>{{ genre }}</p></a>
{% endfor %}
<a href="#" onclick="getGenreId()">NEXT</a>
</div>
{% endblock %}
最佳答案
经过一番摸索,我终于找到了解决这个问题的方法。将成功函数添加到重定向到另一个路由的 ajax 调用中。
mypage.js
$.ajax({
url: Flask.url_for('genre_picks'),
type: "POST",
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(genres),
success: function(response) {
window.location.href = response.redirect
}
});
初始化
@app.route('/genre_picks', methods=["POST", "GET"])
def genre_picks():
if request.method == "POST":
genres = request.json
return jsonify({'redirect': url_for("example", path=genres)})
@app.route('/example/<path>')
def example(path):
genres = path
return render_template("example.html", genres=genres)
关于javascript - 通过 ajax 调用在 Flask 中渲染模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63127252/