如果我很好地理解了您想要的内容并加以区分,则可以在javascript中通过事件类型测试事件类型,然后再通过“ POST”发送数据,如下所示:
if(window.event.type === 'submit'){
// You are sending data
} else {
// You are validating data
}
,
它对我有用,可以正确打印“已提交”。
我可以建议的解决方案是使用一些隐藏的输入,这些输入仅在单击提交按钮时才发送。
<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"
本文链接:https://www.f2er.com/3095860.html