Friday 22 December 2017

javascript - Flask redirect(urlfor()) doesn't reload the page





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






src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js">






{{ 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...