【问题标题】:How can I control the flow of using JavaScript first and then send the control to the back end server created using flask framework?如何先控制使用 JavaScript 的流程,然后将控制发送到使用烧瓶框架创建的后端服务器?
【发布时间】:2020-11-19 03:47:27
【问题描述】:

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

我想在前端使用JavaScript来验证用户在表单字段中提供的数据,然后如果一切正常,那么我想将用户提供的数据发送到后端服务器并进行处理使用python..

但是如何控制当用户点击提交按钮时,控件会转到 JavaScript 代码,然后经过验证后,将数据发送到后端服务器的过程

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

我遇到的麻烦是,填写表单后,当用户单击提交按钮时,控件可以正常执行为验证表单而编写的 Java Script 函数,但即使 Java Script返回false,控件自动转到后端服务器。

但我想做的是,如果 Java 脚本返回 false,控件应该停在那里并要求用户再次填写表单。

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>

【问题讨论】:

    标签: javascript python forms flask linker


    【解决方案1】:

    简单: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>
    

    【讨论】:

    • 如果我这样做,当用户点击提交按钮时,控件将转到前端的JavaScript,那么它如何在验证后发送回服务器?
    • 当函数返回true时,会调用正常的动作路径
    【解决方案2】:

    示例中的 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
    

    【讨论】:

      【解决方案3】:

      代码中唯一的问题在于html中的form标签,

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

      通过这段代码,如果JavaScript函数返回true,那么页面将被重定向到表单标签的action字段中写的url 如果 JavaScript 函数返回 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>

      【讨论】:

        猜你喜欢
        • 2017-05-06
        • 2019-04-03
        • 1970-01-01
        • 1970-01-01
        • 2018-07-14
        • 2017-12-21
        • 1970-01-01
        • 2021-09-05
        • 2013-03-21
        相关资源
        最近更新 更多