3 javascript jquery jinja2 flask
在 中menu.html,单击给定链接会pasta.html以如下方式呈现所选页面 :
<ul>
<li><a href="{{ url_for('pasta') }}";>Pasta</a>
<form action="{{ url_for('handle_menu') }}" method="post">
<input type="radio" name="additive" value="Cheese"> <label style="font-size: 11px;">Cheese</label>
</form>
</li>
Run Code Online (Sandbox Code Playgroud)
但假设@app.route('/pasta')在“完成”之前必须“烹饪”一些“原料”:
@app.route('/pasta')
def pasta():
# (perform some long task here)
return render_template('pasta.html')
Run Code Online (Sandbox Code Playgroud)
就此而言,我想/cooking在页面加载时显示一个视图,如下所示:
@app.route('/cooking')
def cooking():
return render_template('cooking.html')
Run Code Online (Sandbox Code Playgroud)
如果我没记错的话,使用Flask和jinja2模板,您可以返回 ( 200) 或重定向 ( 301) 页面,对于任何中间页面,例如loading.html,您需要javascript.
那么,我如何使用javascript这里以便在等待任务完成时cooking.html显示页面,并在任务完成后最终返回它?/pasta
由于您使用的是GET请求,因此您可以将锚标记路由到cooking,呈现cooking.html模板,然后使用window.location.replace()重定向到pasta。中的长任务将在渲染pasta()之前执行。pasta.html
在menu.html:
<a href="{{ url_for('cooking') }}">Pasta</a>
Run Code Online (Sandbox Code Playgroud)
在cooking.html:
<script> window.location.replace('/pasta'); </script>
Run Code Online (Sandbox Code Playgroud)
对于POST请求,您需要将表单值发送到cooking,将它们传递给模板,然后pasta使用 AJAX 再次发送它们,最后在回调函数中重定向。
在menu.html:
<form action="{{ url_for('cooking') }}" method='POST'>
Run Code Online (Sandbox Code Playgroud)
在cooking():
@app.route('/cooking')
def cooking():
return render_template('cooking.html', form_data=request.form['form_data'])
Run Code Online (Sandbox Code Playgroud)
在pasta():
@app.route('/pasta', methods=['GET', 'POST'])
def pasta():
if request.method == 'GET':
render_template('pasta.html')
# (perform some long task here)
return make_response('POST request successful', 200)
Run Code Online (Sandbox Code Playgroud)
在cooking.html:
<script>
$.ajax({
type: 'POST',
url: '/pasta',
data: {
form_data: '{{form_data}}',
},
success: function() {
window.location.replace('/pasta');
}
});
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8843 次 |
| 最近记录: |