【问题标题】:How to read a custom html table information from client side into flask backend如何从客户端读取自定义 html 表信息到烧瓶后端
【发布时间】:2020-08-16 07:16:55
【问题描述】:

我真正想做的如下: 我想允许用户添加他想要的行数并在其中填写信息。在他点击提交按钮后,表格中输入的数据应该由烧瓶处理。我如何从客户端获取自定义表到我的服务器。带有代码演示的答案表示赞赏(因此我是初学者)。

【问题讨论】:

  • 但至少试一试,然后发布您的问题或疑问
  • 我确实尝试过使用 Ajax 但它不起作用,而且我对从表单以外的信息中读取信息也不是很清楚。

标签: javascript html ajax flask backend


【解决方案1】:

这是一个三列表格的例子,用户可以根据需要动态添加任意多的行,然后当点击提交按钮时我们收集数据并将它们发送到服务器,这是客户端代码,我做了一些样式让它看起来很好看。

$("#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. 继续学习,快乐编码 :)

在客户端测试三行

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

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

【讨论】:

  • 我有点怀疑 ind ,tr,input 的论点在各自的函数中是什么意思。
  • 你在谈论这两行$("#data_container tbody tr").each(function(ind, tr) {$(this).find("input").each(function(ind, input) {,jQuery 的.each 需要一个回调函数来循环并在每个元素上调用该回调,并将参数的索引作为参数元素 ex 0, 1, 2 作为第一个参数,元素本身作为第二个参数,由开发人员命名参数,常用的方法是使用描述性名称,这就是我写"tr"的原因和"input" 所以只有我的代码的读者才能轻松理解发生了什么
  • 这里是.each documentation了解更多
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
  • 2013-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多