繁体   English   中英

如何控制首先使用 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 和密码的表单标签以及一个提交按钮。

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

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

在片段中,我给出了一个虚拟示例。 In that my doubt is how to first send the control to the validate_login_form() written in Java Script and then after validation the control should go to the {{url_for('home')}} written in the action part using the Jinja2 template engine

Here the trouble that i am having is, after filling up the form, when the user clicked of the submit button, the control goes fine to the Java Script function written to validate the form but even if the Java Script returns false, the control automatically转到后端服务器。

但我想要做的是,如果 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>

简单: https://www.w3schools.com/jsref/event_onsubmit.asp 那里有你的 go:

 <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
        });
}

烧瓶/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 中的表单标签,

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

By this code if the JavaScript function returns true then the page will be redirected to the url written in the action field of the form tag and if the JavaScript function returns flase then the control will remain in the same page without being redirected. 这样就可以控制流量了

 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM