Flask - 将参数传递给window.location.replace()

时间:2018-02-01 18:45:58

标签: javascript flask

在Flask框架中,我有一个menu.html,带有可点击的链接:

<a href="{{ url_for('loading',name=lunch)}}";>{{ lunch }}</a>

这是相应的网址视图:

@app.route('/loading/<name>')
def loading(name):
    return render_template('loading.html',
                            name=name)

loading.html底部有这个脚本:

<script> window.location.replace('/lunch/{{name}}'); 
</script>

指向正在处理消费任务的最终视图:

@app.route('/lunch/<name>')
    def (name):
        #(long, consuming task)
        return render_template('lunch.html',
                                name=name)

如果点击,例如,在名为&#39; meat&#39;的商品链接上,我得到 404 ,就像这样:

127.0.0.1 - - [01/Feb/2018 16:27:02] "GET /loading?name=meat HTTP/1.1" 404 -

而不是GET /loading/meat 200,正如所料。

那么在这个框架中正确传递调用window.location.replace()的最简单方法是什么?

1 个答案:

答案 0 :(得分:0)

好的,我会使用window.location.href =&#39; path / to / destination&#39;

由于您的等待和API响应,它会像这样(无论如何使用promises)

fetch(url).then((response) => {
 // do something to the response
}).then(() => {
  window.location.href = '/lunch/{{name}}'
})

这将带您进入您正在使用的功能。

对于那些只寻找重定向的人,您可以使用烧瓶库中的重定向。首先从库中导入重定向:

from flask import Flask, render_template, request, redirect, [anything else]

然后我会像这样编写第一个函数:

@app.route('/loading/<string:name>')
def loading(name):
    return redirect(url_for('name',
                            name=name))

这将使用最初单击的名称将您发送到您的函数名称。我也认为在@ app.rout装饰器中放置变量时指定类型是有帮助的,就像我对<string:name>所做的那样,或者如果你有一个id <int:id>