2 回答

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超4個(gè)贊
它對(duì)我有用,它正確打印“提交”。
我可以提出的解決方案是使用一些隱藏的輸入,只有在單擊提交按鈕時(shí)才會(huì)發(fā)送這些輸入。
<input type="hidden" name="isFormSubmitted" value="true" />
更完整的例子:
前端:
<h1>Hello Flask</h1>
<form id="myForm" action="/validate-form" method="POST">
<label>Password</label>
<input name="password" type="password" />
<label>Username</label>
<input name="username" type="text" />
<input type="hidden" name="isFormSubmitted" value="true" />
<label>Validate when I am changed</label>
<input name="validate" type="text" id="validate"/>
<input type="submit" value="Send" />
</form>
<script>
window.onload = function() {
const myForm = document.getElementById("myForm");
const validateInput = document.getElementById("validate");
//input or change event handler
validate.addEventListener("input", function(e) {
const data = new FormData(myForm);
data.set("isFormSubmitted", "false");
fetch('/validate-form', {
method: 'POST',
body: data,
}).then((response) => {
console.log(response);
});
})
}
</script>
后端:
@app.route("/validate-form", methods = ["POST"])
def register():
if request.method == "POST":
print(request.form)
if request.form["isFormSubmitted"] == "true":
print("SUBMITTED")
return "Thanks submitted"
else:
print("FETCH")
return "Thanks fetch"

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超6個(gè)贊
如果我很清楚你想要什么并且為了區(qū)分它,你可以在通過“POST”發(fā)送數(shù)據(jù)之前在javascript中測(cè)試事件類型,如下所示:
if(window.event.type === 'submit'){
// You are sending data
} else {
// You are validating data
}
添加回答
舉報(bào)