如何从客户端将自定义HTML表信息读取到Flask后端

问题描述

我确切想做的如下: 我想允许用户添加他想要的行数并在其中填充信息。单击“提交”按钮后,应使用flask处理表中输入的数据。如何从客户端获取自定义表到服务器。代码演示的答案表示赞赏(我是初学者)。

解决方法

这里是一个具有三列的表的示例,用户可以根据需要动态地添加任意多的行,然后单击“提交”按钮时,我们将收集数据并将其发送到服务器,这是客户端代码,我做了一些样式使其看起来不错。

$("#add_rows").click(function() {
      // each click on the `+` button adds a row to the table
      $("#data_container tbody").append(`<tr><td><input type="text"></td><td><input type="text"></td><td><input type="text"></td></tr>`);
    });
    $("#submit_rows").click(function() {
      // `obj` for storing the inputs,and the `n` to make unrepeated keys
      var obj = {},n = 0;
      // loop over the rows
      $("#data_container tbody tr").each(function(ind,tr) {
        // add an array to the object
        obj[`r${n}`] = [];
        // loop over the inputs of this row
        $(this).find("input").each(function(ind,input) {
          // add the value of the input to the array and make sure to remove any semicolon since
          // we will use it to separate the inputs
          var val = input.value.replace(/;/g,"");
          obj[`r${n}`].push(val);
        });
        // no need for the array,just join it to a string of values separated by semicolons
        obj[`r${n}`] = obj[`r${n}`].join(";");
        // increase the value of `n`
        n++;
      });
      // log the object to the console so you can see what we are sending
      console.log(obj);
      // send the data to the server,see the console for a logging message for success
      $.post("http://127.0.0.1:3000",obj,(data,status) => console.log("Status: " + status));
    });
* {
  box-sizing: border-box;
}
#data_container {
  border: 1px solid green;
  width: 500px;
  border-radius: 5px;
  padding: 3px;
  background: radial-gradient(lightgreen,green);
  position: relative;
  font-family: monospace;
  font-size: 24px;
}
#data_container th {
  background-color: lightgreen;
  color: white;
  border-radius: 5px 5px 0 0;
}
#data_container td,th {
  width: 33%;
  height: 40px;
  border: 1px solid green;
}
#data_container input {
  width: 100%;
  height: 100%;
  border-color: #aaa;
  font-size: 24px;
}
#add_rows,#submit_rows {
  height: 50px;
  position: absolute;
  background-color: lightgreen;
  font-weight: bold;
  cursor: pointer;
  outline: none;
  font-size: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: yellow;
}
#add_rows {
  width: 50px;
  bottom: -25px;
  right: -25px;
  border-radius: 50%;
  font-size: 48px;
}
#submit_rows {
  width: 100%;
  bottom: -30px;
  left: 0;
  border-bottom-left-radius: 50%;
  z-index: -1;
  font-variant: small-caps;
  letter-spacing: 10px;
  align-items: flex-end;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="data_container">
  <form>
    <table>
      <thead>
        <tr><th>Name</th><th>Job</th><th>Country</th></tr>
      </thead>
      <tbody>
        <tr><td><input type="text"></td><td><input type="text"></td><td><input type="text"></td></tr>
      </tbody>
    </table>
  </form>
  <button id="submit_rows">Submit</button>
  <button id="add_rows">+</button>
</div>

这是后端代码,因为您使用的是 Flask ,所以我也做了同样的事情

from flask import Flask,request,render_template

app = Flask(__name__)

@app.route('/',methods=['GET','POST'])
def get_table_data():
  # if the method is POST then the user is submitting a form otherwise he's just requesting the rendered document page
  if request.method == "POST":
    print("Posting data")
    for input in request.form:
      row = request.form[input].split(";")
      print("--------------------------")
      print("Name: " + row[0]);
      print("Job: " + row[1]);
      print("Country " + row[2]);
      # I'm just printing it but you can do whatever you want with the data
  # always the same page only for testing
  return render_template("Table_send.html")

app.run(host = '127.0.0.1',port = 3000,debug = False)

如果您不熟悉Flask,则需要了解以下内容:

  1. 在与服务器的python脚本相同的目录中创建一个名为"templates"的文件夹
  2. 正常运行脚本,例如python server.py,不需要Flask run ...和添加环境变量...
  3. 保持学习和快乐的编码:)

在客户端测试三行

enter image description here

从后端获取数据并打印出来

Posting data
--------------------------
Name: Bobby
Job: Programmer
Country Canada
--------------------------
Name: Maria
Job: Designer
Country USA
--------------------------
Name: Michael
Job: Instructor
Country Germany