烧瓶模板不会重新渲染

时间:2018-08-20 18:15:30

标签: javascript python flask

一旦触发事件,我将尝试重新呈现烧瓶模板(index.html)。这是我要执行的操作的简化版本:页面最初呈现,并且控制台显示一些文本(“初始数据”)。然后,用户单击按钮,页面将重新渲染一些新数据(“新数据”)。在真实版本中,python代码对数据进行了一些更重的处理,因此无法使用纯HTML / JS进行此操作,我需要重新渲染页面。

这是当前设置:

main.py

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

templates / 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,但是没有使用new参数重新呈现index.html。我已经尝试了该行的各种选项,例如return render_template("index.html", val="New Data")return redirect("index.html", val="New Data"),但是没有什么用新数据重新渲染模板。

谢谢。

2 个答案:

答案 0 :(得分:1)

您不能通过这种方式使用重定向。使用重定向时,它将重定向到flask视图,然后在该视图中运行所有代码,包括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) }
        })
    }

答案 1 :(得分:0)

正如@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>
相关问题