我有下面的python代码:
@restServer.route("/sendData", methods=['POST'])
def client():
ID = request.form.get('ID')
name = request.form.get('name')
postcode = request.form.get('postcode')
dateofbirth = request.form.get('dateofbirth')
balance = request.form.get('balance')
description = request.form.get('description')
insert_stmt = (
"INSERT INTO clients (ID, name, postcode, dateofbirth, balance, description) "
"VALUES (%s, %s, %s, %s, %s, %s)"
)
data = (ID, name, postcode, dateofbirth, balance, description)
cursor.execute(insert_stmt, data)
conn.commit()
print("Did we do it?")
return jsonify(data)
我还有下面的html代码:
<form method="POST">
<p>ID of your Avenger:</p> <input type="number" id="ID" required>
<p>Name of your Avenger:</p> <input type="text" id="name" required>
<p>Post Code of your Avenger:</p> <input type="text" id="postcode" required>
<p>Date of Birth of your Avenger:</p> <input type="date" id="dateofbirth" required>
<p>Bank balance of your Avenger:</p> <input type="number" id="balance" required>
<p>Description of your Avenger:</p> <input type="text" id="description" required>
<button class="button1" type="button" id="hashButton" onclick="nameInput()">Submit</button></form>
最后是下面的javascript代码:
function nameInput() {
var words = document.getElementById("ID", "name", "postcode", "dateofbirth", "balance", "description" ).value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
document.getElementById("nameInputReturn").innerHTML =
json.name;
}
}
xhttp.open("POST", "http://127.0.0.1:5000/sendData", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
xhttp.send(words);
}
我正在努力使它,以便您可以输入数据到表单中,然后它会上传到数据库中的数据。我已经知道如何输入我在代码中指定的数据,只需更改 data = (ID, name, postcode, dateofbirth, balance, description)
线路。当前,单击submit按钮,但数据库只添加一行,该行的每一列都为null。
我对 flask 还很陌生,所以非常感谢您的帮助!
1条答案
按热度按时间93ze6v8z1#
你的前端有点乱。好像你想把
POST
通过js请求,当你的html可以做得更好,更容易。尝试从提交按钮中删除侦听器,并将打开窗体标记更改为
<form method="POST" action="http://127.0.0.1:5000/updateName">
.你也应该改变你所有的习惯
id
属性name
. 这是因为id
属性未发送到服务器。但是,name属性被发送并用于从服务器访问表单的信息。这应该是一个好的开始: