Почему моя страница не перенаправляется после отправки сообщения? - PullRequest
1 голос
/ 12 января 2020

Код ниже, кажется, работает правильно. Сообщение проходит, и я даже вижу сообщение GET на консоли для страницы, на которую я перенаправляю. Но мой браузер не переключается на новую страницу с надписью «Hello». Если я перехожу к / PostTest напрямую, то он работает.

Я также получаю сообщение "Welcome".

</script>
<!DOCTYPE html>
<head>
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<html>
  <body>
<div class="row"></div>
Any Day Drinking Club's Six Nations Table Generator
<div class="row">
  <div class="input-field col s6 offset-m2 offset-l4 m4 l2">
    <input placeholder="Username" id="username" type="text" />
  </div>
  <div class="input-field col s6 m4 l2">
    <input placeholder="Password" id="password" type="password" />
  </div>
</div>
<div class="row">
  <a class="waves-effect waves-light btn" id="loginbutton">Login</a>
</div>
<script>$("#loginbutton").click(function(){
  $.ajax({
    type: 'POST',
    url: "/loginsubmit",
    success: function(){
      alert("Welcome ");
      }
    }
  )
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script></body>
</html>
from flask import Flask, request, redirect, url_for
import yaTemplates as Templates

app = Flask(__name__)

@app.route('/')
def index():
    return Templates.login()

@app.route('/PostTest')
def test():
    return 'Hello'

@app.route("/loginsubmit", methods=["POST"])
def loginsubmit():
    # + request.json["username"]
    return redirect(url_for('test'))


app.run(debug=True)

1 Ответ

2 голосов
/ 12 января 2020

Это потому, что вы используете AJAX .. Вы программно отправляете запрос через браузер, за сценой, который является отдельным и не связан с тем, что вы видите на экране.

В Flask, вам нужно будет ответить с URL, чтобы перенаправить на. На стороне клиента вам нужно установить window.location для этого URL.

РЕДАКТИРОВАТЬ: в виде небольшой демонстрации, вы можете открыть браузер Инструменты разработчика (щелкните правой кнопкой мыши на любой веб-страницу, выберите «Проверить элемент»), затем выберите вкладку «Консоль» и введите window.location = "https://google.com", затем нажмите enter, и ваш браузер изменит URL-адрес и перейдет к Google.

enter image description here

from flask import Flask, request, redirect, url_for
import yaTemplates as Templates

app = Flask(__name__)

@app.route('/')
def index():
    return Templates.login()

@app.route('/PostTest')
def test():
    return 'Hello'

@app.route("/loginsubmit", methods=["POST"])
def loginsubmit():
    # + request.json["username"]
    return url_for('test')


app.run(debug=True)

Клиентская сторона:

<script>
  $("#loginbutton").click(function () {
    $.ajax({
      type: 'POST',
      url: "/loginsubmit",
      success: function (url) {
        window.location = url;
      }
    })
  });
</script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...