这个问题在这里已有答案:
我有一个页面,有一个按钮,使ajax
post
到flask
路线。我想要计算消息的路由(通过硬编码简化示例)并将其传递回另一个路由并重新加载用户所在的页面。 redirect(urlfor())
确实调用了另一条路线,但render_template
似乎没有被调用,因为页面没有重新加载。
init.朋友
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
@app.route('/second_route', methods=['POST'])
def second_route():
print request.json
return redirect(url_for('hello_world', message='test'))
@app.route('/')
def hello_world(message=None):
return render_template('index.html', message=message)
app.run()
的index.html
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#mybutton').click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/second_route",
data: JSON.stringify({}),
success: [],
dataType: "json"
});
});
});
</script>
</head>
<body>
{{ message }}
<button id="mybutton" name="mybutton" type="button">Click Me!</button>
</body>
</html>
afAX无法处理重定向响应。但是,您可以将{{message}}
封装在<span id="message">
中,识别元素,然后执行jQuery .html()
以在AJAX完成成功时插入自定义文本。
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/second_route",
data: JSON.stringify({}),
success: [],
dataType: "json"
}).done(function(){
$('#message').html('test');
window.location.href = '/';
}).fail(function(response){
$('#message').html(response['responseText']);
});
要重定向,你可以用done
替换window.location.href = "/someURL"
子句中的代码,但由于端点是相同的,所以这不是必需的。这样,根本不需要使用message
变量。
这就是我最终为那些阅读问题的人解决问题的方法。
将我的帖子请求更改为发布到同一路由,通过此调用加载页面:
var posting = $.post(window.location.href, {'some key': 'some value'});
posting.done(function( ) {
window.location.replace(window.location.href);
});