簡體   English   中英

為什么Flask中的URL重定向可以在控制台中工作,但現在可以在實際的Web應用程序中工作?

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

我將嘗試僅包含解決我的問題所需的代碼-我試圖在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,然后返回redirect('/')。 我想重定向到主頁@'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);
            }
        });
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM