我有一個帶有一些普通 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)```
uj5u.com熱心網友回復:
使用Fetch API發送資料。
在以下示例中,將資料轉換為符合 JSON 的字串并通過 POST 發送到服務器。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button id="click">Click</button>
<table id="my-table">
<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>
<script type="text/javascript">
(() => {
const tableToJSON = (tableElem) => {
const tableRows = Array.from(tableElem.rows);
const tableHead = Array.from(tableRows[0].cells).map(cell => {
return cell.innerHTML.toLowerCase().replace(/ /g,'_')
});
return tableRows.slice(1).map(row => {
const rowData = {}
Array.from(row.cells).forEach((cell, i) => {
return rowData[tableHead[i]] = cell.innerHTML;
});
return rowData;
});
};
const btnElem = document.getElementById('click');
btnElem.addEventListener('click', (evt) => {
const tableElem = document.getElementById('my-table');
const tableData = tableToJSON(tableElem);
// Post JSON data to the server.
const url = '/data';
fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(tableData)
}).then(resp => resp.json())
.then(data => console.log(data));
});
})();
</script>
</body>
</html>
然后,您可以使用 請求和處理服務器上的資料request.get_json()。來自服務器的回應是一個使用jsonify轉換的簡單 JSON 物件。
from flask import Flask
from flask import render_template, request, jsonify
app = Flask(__name__)
app.secret_key = 'your secret here'
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
@app.route('/data', methods=['POST'])
def data():
data = request.get_json()
print(data)
return jsonify(success=True)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/325160.html
標籤:javascript Python html json 烧瓶
