如何创建一个 if 语句来查找获取请求?

我正在使用 Flask 和 Fetch()


我有一个表单当文本输入“a”更改/输入文本时。一个获取请求被发送到“/validate-form”。


当表单末尾的提交按钮被按下时。它也将表单提交到“/validate-form”。


我可以创建什么 If else 语句,它将能够区分是发送获取请求还是提交表单到“/validate-form”


我已经尝试了下面的方法,但是“FETCH”一直被打印到终端上。


@app.route("/validate-form", methods = ["POST"])

def register():

    if request.method == "POST":

        if "username" in request.form and "password" in request.form:

           print("submitted")

           return "Thanks"

        else:

            print("FETCH")

            return "Thanks"


潇湘沐
浏览 213回答 2
2回答

繁星coding

它对我有用,它正确打印“提交”。我可以提出的解决方案是使用一些隐藏的输入,只有在单击提交按钮时才会发送这些输入。<input type="hidden" name="isFormSubmitted" value="true" />更完整的例子:前端:<h1>Hello Flask</h1><form id="myForm" action="/validate-form" method="POST">&nbsp; &nbsp; <label>Password</label>&nbsp; &nbsp; <input name="password" type="password" />&nbsp; &nbsp; <label>Username</label>&nbsp; &nbsp; <input name="username" type="text" />&nbsp; &nbsp; <input type="hidden" name="isFormSubmitted" value="true" />&nbsp; &nbsp; <label>Validate when I am changed</label>&nbsp; &nbsp; <input name="validate" type="text" id="validate"/>&nbsp; &nbsp; <input type="submit" value="Send" /></form><script>window.onload = function() {&nbsp; const myForm = document.getElementById("myForm");&nbsp; const validateInput = document.getElementById("validate");&nbsp; //input or change event handler&nbsp; validate.addEventListener("input", function(e) {&nbsp; &nbsp; const data = new FormData(myForm);&nbsp; &nbsp; data.set("isFormSubmitted", "false");&nbsp; &nbsp; fetch('/validate-form', {&nbsp; &nbsp; &nbsp; method: 'POST',&nbsp; &nbsp; &nbsp; body: data,&nbsp; &nbsp; }).then((response) => {&nbsp; &nbsp; &nbsp; &nbsp; console.log(response);&nbsp; &nbsp; });&nbsp; })}</script>后端:@app.route("/validate-form", methods = ["POST"])def register():&nbsp; &nbsp; if request.method == "POST":&nbsp; &nbsp; &nbsp; &nbsp; print(request.form)&nbsp; &nbsp; &nbsp; &nbsp; if request.form["isFormSubmitted"] == "true":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;print("SUBMITTED")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return "Thanks submitted"&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("FETCH")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return "Thanks fetch"

哈士奇WWW

如果我很清楚你想要什么并且为了区分它,你可以在通过“POST”发送数据之前在javascript中测试事件类型,如下所示:&nbsp; &nbsp;if(window.event.type === 'submit'){&nbsp; &nbsp; &nbsp; &nbsp; // You are sending data&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp;// You are validating data&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript