【问题标题】:How would I be able to send a Popup upon submitting a form when a user doesn't exist?当用户不存在时,如何在提交表单时发送弹出窗口?
【发布时间】:2021-12-13 13:55:08
【问题描述】:

我正在创建一个登录和注册系统,并且在登录时,如果用户不存在,我想返回一个弹出消息“请先注册”,然后在弹出窗口中返回一个“确定”按钮,按下该按钮将发送用户回到主页'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>

谢谢

【问题讨论】:

    标签: html flask sqlalchemy


    【解决方案1】:
    1. 从您的代码中,当用户单击提交时,您将直接提交表单,并且您正在执行return render_template,这意味着您正在返回整个页面(新页面)。

    2. 如果您在上述代码中使用flash,它只会在您返回的“新”页面顶部显示消息。

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

    a) 在表单提交时,拦截它

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

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

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

    d) 你的 python 代码不应该返回 render_template。您应该只返回一个值,让您知道一切是成功还是失败

    【讨论】:

      猜你喜欢
      • 2020-03-24
      • 2012-01-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      相关资源
      最近更新 更多