如何先控制使用 JavaScript 的流程,然后将控制发送到使用 flask 框架创建的后端服务器?

How can I control the flow of using JavaScript first and then send the control to the back end server created using flask framework?

我正在使用 Flask 框架.. 我在前端有一个用于登录 ID 和密码的表单标签以及一个提交按钮。

我想在前端使用Java脚本来验证用户在表单域中提供的数据,然后如果一切正常,那么我想将用户提供的数据发送到后端服务器并使用 python..

对其进行处理

但是我如何控制当用户点击提交按钮时控件将转到Java脚本代码然后在验证后将数据发送到后端服务器

在代码片段中,我给出了一个虚拟示例。因为我的疑问是如何首先将控件发送到 validate_login_form() 编写在 Java 脚本中,然后在验证之后控件应该转到 {{url_for('home')}} 写在 action 部分使用 Jinja2模板引擎

我遇到的问题是,填写完表格后,当用户单击提交按钮时,控件会正常运行 Java 脚本函数来验证表单,但即使 Java 脚本 returns 为假,控件也会自动转到后端服务器。

但我想做的是,如果 Java 脚本 returns 为假,控件应停在那里并要求用户再次填写表格。

function validate_login_form(){
    let login_id = document.getElementById('login_id').value
    let password = document.getElementById('password').value

    if(login_id == '' && password == ''){
        alert('please enter the login id and password')
        return(false)
    }
    else if(login_id == '' && password != ''){
        alert('please enter the login id')
        return(false)
    }
    else if(login_id != '' && password == ''){
        alert('please enter the password')
        return(false)
    }
    else{
        if(login_id == 'test' && password == 'test'){
            return(true);
        }
        else{
            alert('please enter the valid login id and password')
            return(false)
        }
    }
}
<html>
    <head>
    </head>
    <body>        
        <form action="{{url_for('home')}}" onsubmit="validate_login_form()">
            <label for="login_id">LogIn</label>
            <input type="text" name="login_id" placeholder="login Id" id="login_id">
            <label for="password">Password</label>
            <input type="password" name="password" placeholder="password" id="password">
    
            <br><br>
            <input type="submit" value="submit" >
        </form>
        <script src="{{ url_for('static', filename='scripts/login.js') }}"></script>
    </body>
</html>

简单:https://www.w3schools.com/jsref/event_onsubmit.asp。 开始吧:

 <form onsubmit="myFunction()">
  Enter name: <input type="text">
  <input type="submit">
</form> 

<script>
function myFunction() {
    return true;
}
</script>

HTML 来自示例:

<form method="POST" id="myForm">
    <input type="email" name="email" id="email"/>
    <input type="password" name="password" id="password"/>
    <button type="submit">Login</button>
</form>

javascript:

var myForm = document.getElementById("myForm");
myForm.onsubmit = function(e){
    e.preventDefault();


    // validate here and produce data


    fetch('/mypage', {
        method: "POST",
        credentials: "include",
        cache: "no-cache",
        body: data,
        headers: new Headers({
          "Content-Type": "application/json",
        }),
      })
       .then((response) => {
          if (response.status !== 200) {
            // handling if status is not ok(200)
          }
          response.text().then((res) => {
            // response handling

            if(res === "success"){
               // redirect to homepage or do anything
            } else {
               // something went wrong
            }
          });
        })
        .catch((err) => {
            // error handle
        });
}

Flask/Python:

from flask import request
@app.route('/mypage', methods=['GET', 'POST'])
def myPage():
    if request.method == "POST" and request.json:
          data = request.json
         
          # send data to database

          return 'success', 200

代码中唯一的问题是在 html、

中的 form 标签中

我应该写 onsubmit=return validate_login_form() 而不是 onsubmit=validate_login_form()

通过这段代码,如果 JavaScript 函数 returns true 那么页面将被重定向到 url 写在 表单标签的操作字段 如果 JavaScript 函数 returns flase 那么控件将保留在同一页面中而不会被重定向。 这样才能控制流量

function validate_login_form(){
    let login_id = document.getElementById('login_id').value
    let password = document.getElementById('password').value

    if(login_id == '' && password == ''){
        alert('please enter the login id and password')
        return(false)
    }
    else if(login_id == '' && password != ''){
        alert('please enter the login id')
        return(false)
    }
    else if(login_id != '' && password == ''){
        alert('please enter the password')
        return(false)
    }
    else{
        if(login_id == 'test' && password == 'test'){
            return(true);
        }
        else{
            alert('please enter the valid login id and password')
            return(false)
        }
    }
}
<html>
    <head>
    </head>
    <body>        
        <form action="{{url_for('home')}}" onsubmit="return validate_login_form()">
            <label for="login_id">LogIn</label>
            <input type="text" name="login_id" placeholder="login Id" id="login_id">
            <label for="password">Password</label>
            <input type="password" name="password" placeholder="password" id="password">
    
            <br><br>
            <input type="submit" value="submit" >
        </form>
        <script src="{{ url_for('static', filename='scripts/login.js') }}"></script>
    </body>
</html>