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

标签 javascript html flask

我将尝试仅包含解决我的问题所需的代码 - 我试图在 Flask 中的另一个函数中重定向到我的主页('/' - index.html),但它在浏览器。但它在 Web 控制台中显示了正确的响应 (Firefox)

应用程序.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);
            }
        });
    });
});

注册.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 的代码。

最佳答案

如果您使用 javascript 提交 singUp 表单,则还必须使用 javascript 重定向客户端。 singUp() 函数中的 return redirect('/') 行只是重定向 Ajax 请求,但客户端仍然在 singup 页面上。您应该返回状态代码而不是该行:return json.dumps({'status': 'ok'}) 并像这样重定向客户端:

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);
            }
        });
    });
});

关于javascript - 为什么 Flask 中的 URL 重定向在控制台中有效,但现在在实际的 Web 应用程序中有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33730502/

相关文章:

javascript - 如何使用 CSS 和 javascript 为 X 数量的 div 设置动画?

html - 绝对定位的子 div 离开父 div

python - Alembic 可以自动生成列更改吗?

javascript - 数据从 HTML 文本输入传递到 python 脚本

javascript - 绘制自定义形状和弯曲矩形

javascript - Ng-repeat 整数值

html - 如何让这个页面在 IE 9 中居中

python - 在 Heroku 上运行 Telethon

python - 在 Python Cloud Function 中使用 errorhandler 返回 JSON

javascript - 使用 xlsx npm 包将表格数据下载为 xlsx