简体   繁体   中英

Why does URL Redirect in Flask work in console but now in the actual web app?

I'll try to include only the necessary code to solve my problem -- I am trying to redirect to my home page ('/' - index.html) in another function in Flask, but it does not work in the browser. It shows the correct response in the web Console though (Firefox)

app.py

from flask import Flask, render_template, json, request, redirect, session, flash
from flask.ext.mysql import MySQL
from werkzeug import generate_password_hash, check_password_hash

@app.route('/')
def main():
    return render_template('index.html')

@app.route('/showSignUp')
def showSignUp():
    return render_template('signup.html')

@app.route('/signUp',methods=['POST','GET'])
def signUp():
    try:
        # read the user posted values from the UI
        _name = request.form['inputName']
        _email = request.form['inputEmail']
        _password = request.form['inputPassword']

        # validate the received values
        if _name and _email and _password:

            # sql stuff
            if len(data) is 0:
                flash('User account created successfully.')
                return redirect('/')
            else:
                return json.dumps({'error':str(data[0])})
        else:
            return json.dumps({'html':'<span>Enter the required fields</span>'})

    except Exception as e:
        return json.dumps({'error':str(e)})
    finally:
        # close sql stuff


if __name__ == "__main__":
    app.run(debug=True, port=5002)

signUp.js

$(function(){

    $('#btnSignUp').click(function(){
        $.ajax({
            url: '/signUp',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response){
                console.log(response);
            },
            error: function(error){
                console.log(error);
            }
        });
    });
});

signup.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>wApp</title>


    <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
    <link href="../static/css/signup.css" rel="stylesheet">
    <script src="../static/js/jquery-1.11.3.js"></script>
    <script src="../static/js/signUp.js"></script>

  </head>

  <body>

    <div class="container">
      <div class="header">
        <nav>
          <ul class="nav nav-pills pull-right">
            <li role="presentation" ><a href="/">Home</a></li>
            <li role="presentation"><a href="/showSignin">Sign In</a></li>
            <li role="presentation" class="active"><a href="#">Sign Up</a></li>
          </ul>
        </nav>
        <h3 class="text-muted">wApp</h3>
      </div>

      <div class="jumbotron">
        <h1>wApp</h1>
        <form class="form-signin" action="/signUp" method="post">
        <label for="inputName" class="sr-only">Name</label>
        <input type="name" name="inputName" id="inputName" class="form-control" placeholder="Name" required autofocus>
        <label for="inputEmail" class="sr-only">Email address</label>
        <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
        <label for="inputPassword" class="sr-only">Password</label>
        <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password" required>

        <button id="btnSignUp" class="btn btn-lg btn-primary btn-block" type="button">Sign up</button>
      </form>
      </div>

    </div>
  </body>
</html>

I've omitted a bunch of stuff, but is there anything glaringly wrong here? The relevant portion is the flash and return redirect('/'). I want to redirect to the main page @ 'index.html' This displays the result in the web Console, but in the web application nothing happens. My html index page has the code for receiving the flash as well.

If you submit the singUp form using javascript, you have to redirect the client using javascript as well. The return redirect('/') line in the singUp() function just redirects the Ajax request, but the client is still on the singup page. Instead of that line you should return a status code: return json.dumps({'status': 'ok'}) and redirect the client like this:

signUp.js

$(function(){    
    $('#btnSignUp').click(function(){
        $.ajax({
            url: '/signUp',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response){
                window.location.href = "http://example.com";
            },
            error: function(error){
                console.log(error);
            }
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM