2 回答

TA貢獻1797條經驗 獲得超4個贊
它對我有用,它正確打印“提交”。
我可以提出的解決方案是使用一些隱藏的輸入,只有在單擊提交按鈕時才會發送這些輸入。
<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貢獻1799條經驗 獲得超6個贊
如果我很清楚你想要什么并且為了區分它,你可以在通過“POST”發送數據之前在javascript中測試事件類型,如下所示:
if(window.event.type === 'submit'){
// You are sending data
} else {
// You are validating data
}
添加回答
舉報