为什么Flask中的URL重定向在控制台中工作,但现在在实际的Web应用程序中?

时间:2015-11-16 07:44:24

标签: javascript html flask

我将尝试仅包含必要的代码来解决我的问题 - 我试图在Flask中的另一个函数中重定向到我的主页('/' - index.html),但它不能在浏览器。它在Web控制台中显示正确的响应(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>

我省略了一堆东西,但这里有什么明显的错误吗?相关部分是flash并返回重定向('/')。我想重定向到主页面''index.html'这会在Web控制台中显示结果,但在Web应用程序中没有任何反应。我的html索引页面也有接收flash的代码。

1 个答案:

答案 0 :(得分:3)

如果您使用javascript提交singUp表单,则必须使用javascript重定向客户端。 NSShadow *shadow = [NSShadow new]; [shadow setShadowColor:self.shadowColor]; [shadow setShadowOffset:self.offset]; UIColor* strokeColor = self.outlineColor; UIColor* fontColor = [self titleColorForState:UIControlStateNormal]; NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:self.titleLabel.text attributes:@{ NSShadowAttributeName:shadow, NSStrokeWidthAttributeName:[NSNumber numberWithFloat:(-1 * self.outlineWidth)], NSStrokeColorAttributeName: strokeColor, NSForegroundColorAttributeName: fontColor}]; [self setAttributedTitle:attributedText forState:UIControlStateNormal]; 函数中的return redirect('/')行只是重定向Ajax请求,但客户端仍在单元页面上。您应该返回状态代码singUp()而不是该行,并重定向客户端,如下所示:

<强> signUp.js

return json.dumps({'status': 'ok'})