【问题标题】:Render template in Flask from ajax call从 ajax 调用在 Flask 中渲染模板
【发布时间】:2020-11-17 11:43:13
【问题描述】:

在这方面遇到了困难。我正在通过 Ajax 将一些数据发送到正在处理它的 Flask 服务器路由,希望然后用处理后的数据呈现一个新模板。数据似乎从我的 Javascript 流向我的 Flask 服务器。 (我正在为 Flask.url_for 使用 JSGlue。)但是一旦它“返回 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>

genres.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 %}

【问题讨论】:

  • 你定义了methods=["GET"] - 所以它不能得到POST - 你需要methods=["GET", "POST"]
  • 您是否使用Flask 模板生成了mypage.js?如果不是,那么您不能使用Flask.url_for('get_genres')。如果您使用Flask tempalte 生成它,那么它可能应该使用{{ url_for(...) }}
  • 1.您的路线需要接受 POST 2。如果您从 post 请求返回 html,则更正常的是返回页面上的部分以重绘而不是整个页面。然后(如果使用 JQuery)在 success 的回调函数中执行类似 $("#ajaxgenerated").html(data); 的操作
  • 已编辑以包含“POST”。那在我的代码中,不知道为什么我在输入这个问题时将其删除。即使使用它,它仍然无法正常工作。另外,我正在使用允许 Flask.url_for 的 JSGlue,并且我已经对其进行了测试。还有其他想法吗?感谢您的帮助。

标签: javascript python ajax templates flask


【解决方案1】:

经过大量的挖掘,我终于设法找到了解决这个问题的方法。向重定向到另一个路由的 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)

【讨论】:

  • 您建议的解决方案毫无意义。为什么要进行 Ajax 调用,以便在客户端接收重定向 URL,然后执行该重定向 URL 以发出新的整页服务器端请求?
  • 我的主要原因是因为我不希望在页面呈现时变量出现在 url 中。我想将其保留为 mysite.me/example,而不是 mysite.me/example?long_string_of_variables_......我在搜索中找不到任何其他解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-13
  • 1970-01-01
  • 2018-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-27
相关资源
最近更新 更多