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
}
添加回答
举报
