我有一个带有一些香草 Javascript 的 Flask 应用程序(我不知道 JQuery)。它执行以下操作: (1) 用户在 HTML 表中输入一些数据。(2) 然后将数据解析为 JSON。(3) 我想将 JSON 文件发布到服务器。(4) 从服务器,JSON 对象被发布到不同的 REST API 以供进一步使用。
步骤 1、2 和 4 工作(我可以console.log使用 JSON 对象),但我不知道如何将 JSON 对象从客户端发布到服务器。我一直看到的选项是在标签之间移动表格,然后通过request.form. 我很高兴这样做,但与在客户端解析 JSON 并将干净的对象发布到第三方 REST API 可以立即使用的服务器相比,这似乎很笨拙。我在这里想念什么?
<!DOCTYPE html>
<html>
<body>
<body>
<button id="click">Click</button>
<table id="myTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>001</td>
<td>Trousers</td>
<td>9.99</td>
</tr>
<tr>
<td>002</td>
<td>Shirt</td>
<td>19.99</td>
</tr>
<tr>
<td>003</td>
<td>Shoes</td>
<td>49.99</td>
</tr>
</tbody>
</table>
</body>
<script>
const btn = document.getElementById("click");
btn.addEventListener("click", function () {
tableToJson(table);
})
let table = document.getElementById("myTable");
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
}
// go through cells
for (var i=1; i<table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j=0; j<tableRow.cells.length; j++) {
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
console.log(data);
return data;
}
</script>
</html>
app = Flask(__name__) # Create an Instance
@app.route('/', methods=['GET', 'POST']) # Route the Function and allow Requests
def main(): # Run the function
if request.method == 'POST': # Identify Request Method
value = request.form['input'] # Gather the Post Request
return value
if request.method == 'GET': # Identify Request Method
return render_template('index.html')
app.run(host='0.0.0.0', port=5000, debug=True) # Run the Application (in debug mode)```