当用户不存在时,我如何能够在提交表单时发送弹出窗口?

How would I be able to send a Popup upon submitting a form when a user doesn't exist?

我正在创建一个登录和注册系统,在登录后,如果用户不存在,我想 return 弹出消息“请先注册”,然后是 'OK' 按钮在弹出窗口中,按下时会将用户送回主页 'index.html'。输入密码错误也是一样。

这里是 main.py 的登录部分:

@app.route("/login", methods = ['GET', 'POST'])
def login():
    if request.method=='GET':
        return render_template("login.html")
    else:
        email = request.form['email']
        password = request.form ['password']
        user = get_user(email)
        
        if user != None: 
          
          if user.password == password:
            return render_template("home.html")
          else:
            return render_template("index.html")
        else:
          return render_template ('index.html')

我尝试使用 flash 但它没有用,登录的 html 部分 (login.html)。

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    <title>DeBank</title>
  </head>
  <body style = "text-align: center; font-family: arial">

    <form action="/login" method="POST">
        <input type="text" name="email" placeholder="email:" required>
        <br>
        <input type="text" name="password" placeholder="password:" required>
        <br>
        <a href = "{{ url_for('index') }} "><input type="submit" value="Submit"></a>
    </form>

    <script src="{{ url_for ('static', filename='js/script.js')}}"></script>
  </body>
</html>

谢谢

  1. 根据您的代码,当用户点击提交时您将直接提交表单,并且您正在执行 return render_template 这意味着您正在 return 整个页面(新页)。

  2. 如果您在上面的代码中使用 flash,它只会在 'new' 页面顶部显示您已 return 编辑的消息.

  3. 要显示弹出窗口,您必须以编程方式提交表单,即当用户单击 submit 按钮时,您需要使用 Javascript 拦截它,然后通过同样 Javascript 对您的服务器执行 asynchronous post。您的服务器输出将 return 编辑到您的代码中。如果登录成功,则重定向用户。如果不是,则触发弹出窗口。本质上,类似(这是一个非常粗略的轮廓)

a) 在表单提交时拦截它

    document.getElementById(<form_id>).onsubmit = function() {

    }

b) 通过 fetch 之类的方式提交您的表格。请参阅此 example,了解如何通过 fetch

提交表单

c) 如果密码不匹配,则触发弹出窗口,否则重定向用户

d) 您的 python 代码 不应 执行 return render_template。您应该 return 一个值,让您知道是一切成功还是失败