簡體   English   中英

Flask 中的渲染模板來自 ajax 調用

[英]Render template in Flask from ajax call

遇到這個困難。 我正在通過 Ajax 將一些數據發送到正在處理它的 Flask 服務器路由,希望然后用處理后的數據呈現一個新模板。 數據似乎從我的 Javascript 流向我的 Flask 服務器。 (我在 Flask.url_for 中使用 JSGlue。)但是一旦它“返回 render_template”,它就會死掉。 我沒有得到任何回溯錯誤或任何東西。 我已經到處嘗試了 print() 和 console.log 來了解是什么殺死了它,但到目前為止我還是一無所獲。 我錯過了一些明顯的東西嗎?

我的頁面.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);
        }
    })

初始化文件

@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)

索引.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 %}

經過大量的挖掘,我終於設法找到了解決這個問題的方法。 將成功的 function 添加到重定向到另一個路由的 ajax 調用。

我的頁面.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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM