I have a page with a button that makes a ajax
post
to a flask
route. I'd like the route to compute a message (simplified by hardcoding for the example) and passes it back to another route and reloads the page the user is on. redirect(urlfor())
does call the other route, but render_template
seems not to be called as the page doesn't reload.
init.py
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
{{ message }}
Answer
AJAX cannot handle a redirect response, afaik. You could, though, encapsulate {{message}}
in a , identify the element, and do a jQuery
.html()
to insert custom text upon AJAX completion success.
$.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']);
});
To redirect, you'd replace the code inside the done
clause with window.location.href = "/someURL"
, but since the endpoint is the same this isn't necessary. This way, using a message
variable at all wouldn't be necessary.
No comments:
Post a Comment