Wednesday 15 July 2015

ajax - How to redirect with Flask and jQuery -


I am using flesk for a personal project which is in the form of my backend and jquery.

To login, I want to do this:

  $ Type ajax ({type: "post", data: json.stringify (body), // username and password content: 'app / jason; charset = utf-8', url: "/ login", success: success Function, error: error function, complete: full function}); In the error message, I will tell the user that their username or password are wrong etc.  

My / login root on the backend looks like this

  @ app.route ("/ login", methods = ['GET', 'POST']) DIF Login (): If (request.method == "POST"): # Recover user name and password sent data = request.json (if there is no data or the data is not 'username' or ' Password '): abort (400) Other: count = user.query.filter (User.username == Data [user name']). Count () if (calculation == 0): isolated (404) # that user does not exist: passIsCorrect = User.query.filter (User.username == data ['user name]], user.password =' ​​'data '[' Password ']) (passIsCorrect): session [' user '] = data [' username '] return redirect (url_for (' index ')) else: abort (401) else: return render_template ( 'Login.html')   

However on the client side, the browser does not redirect and if I completely change the response object in the function If I see, I think that my '/' route will be returned normally: 200 OK an index template. N d.

My question is:

Is there any way that I can stop redirecting the customer?

I think this problem is because Jquery is starting the request and not the browser.

My first attempt to solve this problem was to create a response using the make_response and set the location header, but the result was the same behavior . My current solution is to return 200 and the client does window.location = "/" , but it looks like

Redirects do not work on AJAX calls, browsers do not respect them. Most people implement their custom redirect solutions, returning code 200 and redirecting a URL to the JSN response. Look for some good examples.

As a side note, posting a login form through AJAX does not really give you a lot of advantage, I send the post to the browser as normal and then redirect your flaws function to redirection In order to notify the user of the new page or error, it probably redirects back to the login page on failure with the flash message.

No comments:

Post a Comment