簡體   English   中英

Flask 模板不會重新渲染

[英]Flask template won't re-render

一旦事件被觸發,我試圖重新渲染燒瓶模板(index.html)。 這是我正在嘗試做的簡化版本:最初呈現頁面並且控制台顯示一些文本(“初始數據”)。 然后用戶單擊一個按鈕,頁面會重新呈現一些新數據(“新數據”)。 在真實版本中,python 代碼對數據進行了一些繁重的處理,因此使用純 HTML/JS 無法做到這一點,我確實需要重新渲染頁面。

這是當前的設置:

主文件

from flask import Flask, request, render_template, redirect, Response, url_for    

app = Flask(__name__)

@app.route('/', methods = ['GET'])
def index():
    return render_template(("index.html"), val="Initial Data")

@app.route('/newData', methods = ['GET', 'POST'])
def newData():
    return redirect(url_for("index", val="New Data"))

if __name__ == '__main__':
    app.run()

模板/index.html

<script src='https://code.jquery.com/jquery-3.3.1.min.js'></script>
<body>
    <button onclick='sendData()'>send data</button>
</body>
<script>
    window.onload = function () { console.log({{val}}) };
    function sendData() {
        var str = 'This is some data';
        $.ajax({
            url: '/newData',
            type: 'POST',
            data: str,
            success: function () { console.log('success') },
            error: function (error) { console.log(error) }
        })
    }
</script>

目前發生的事情是當頁面最初呈現時(如預期)“初始數據”出現在控制台中,按鈕單擊調用該函數,然后模板沒有任何反應。 我希望“新數據”接下來出現在控制台中,顯示模板已被重新渲染,但這並沒有發生。 我知道 python 函數 newData 正在被調用,但 index.html 沒有用新參數重新呈現。 我已經嘗試了該行的各種選項,例如return render_template("index.html", val="New Data")return redirect("index.html", val="New Data") ,但沒有任何重新- 使用新數據渲染模板。

謝謝。

您不能以這種方式使用重定向。 當您使用重定向時,它將重定向到燒瓶視圖,然后將運行該視圖中的所有代碼,包括return render_template("index.html", val="Initial Data")

您可以嘗試使用 get 參數:

@app.route('/<val>', methods = ['GET'])
def index(val): 
    return render_template(("index.html"), val=val)

@app.route('/newData/<val>', methods = ['GET', 'POST'])
def newData(val):
    return redirect(url_for("index", val=val))

或者,如果您願意,可以通過執行以下操作,使用現有的 ajax 代碼完成此任務:

from flask import request
@app.route('/newData', methods = ['GET', 'POST'])
def newData():
    return request.data # this will access the data you sent using ajax 
                        # and return it back in the response

在您的 js 代碼中:

window.onload = function () { console.log({{val}}) };
    function sendData() {
        var str = 'This is some data';
        $.ajax({
            url: '/newData',
            type: 'POST',
            data: str,
            success: function (res) { console.log(res) }, 
              // res is the response from the server 
              // (from return request.data)
            error: function (error) { console.log(error) }
        })
    }

正如@shifloni 指出的那樣,你不能這樣做。 如果可以的話,AJAX 調用只會將 http render_template 作為變量返回到 Javascript 中,因此它不會刷新您的瀏覽器。 我能看到的這個最簡單的方法是重組為:

@app.route('/', methods=['GET'], defaults={'val': 'Initial Data'})
@app.route('/<val>', methods=['GET'])
def index(val):
    return render_template(("index.html"), val=val)

並在您的 HTML 中這樣做:

<body>
    <button onclick='sendData()'>send data</button>
</body>
<script>
    var sendData = function() {
        var strData = 'This is some data';
        urlGet = {{ url_for('app.index') }} + '/' + strData
        location.href = urlGet;
    };
</script>

暫無
暫無

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

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