[英]Can't use preventDefault() with if, else
$.get
in the code below returns a boolean value in JSON format named data
.下面代码中的
$.get
返回一个名为data
的 JSON 格式的 boolean 值。 But whether the value of data
is false or true preventDefault()
prevents the submission of the form anyway.但是无论
data
的值是 false 还是 true preventDefault()
都会阻止提交表单。
$(document).ready(function() {
$("#username").blur(function() {
let username = document.getElementById("username").value;
$.get("/check", {
username_value: username
}, function(data) {
alert(data);
$("#submit").click(function(e) {
if (data) {
e.preventDefault();
} else if (!data) {
e.submit();
}
});
});
});
});
And this is the /check part这是 /check 部分
@app.route("/check", methods=["GET"])
def check():
"""Return true if username available, else false, in JSON format"""
get_username = request.args.get("username_value")
users = db.execute("SELECT username FROM users")
lenght = len(get_username)
i = 0
for user in users:
if get_username == users[i]["username"] or not lenght > 1:
return jsonify(True)
i += 1
return jsonify(False)
I am very new at coding business btw.顺便说一句,我对编码业务很陌生。 Thanks for help.
感谢帮助。
Try change to capture the event from form ID instead of button this way:尝试更改以通过这种方式从表单 ID 而不是按钮捕获事件:
$("#form").submit(function (e) {
if (!data) {
e.preventDefault();
} else {
e.submit();
}
});
e.submit() must be used in event from a submited form. e.submit() 必须在提交表单的事件中使用。
Make sure data is boolean type.确保数据为 boolean 类型。 and don't forget change the selector to your form ID.
并且不要忘记将选择器更改为您的表单 ID。
I solve the problem by replacing the $.get
with $.ajax
.我通过将
$.get
替换为$.ajax
来解决问题。 I guess the problem was about the fact that $.get
only works async.我想问题在于
$.get
只能异步工作。 So I used $.ajax
's async paramater at false.所以我使用
$.ajax
的异步参数为假。 Then it worked just as I want.然后它就像我想要的那样工作。
Last version of the code:最新版本的代码:
$(document).ready(function() {
$('#form').submit(function(e){
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
let confirmation = document.getElementById("confirmation").value;
var boolean_data;
$.ajax({url: "/check?username=" + username, type: 'get', async: false, success: function(data){boolean_data=data;}});
if(!boolean_data) {
alert("\"" + username + "\"" + " username is already taken.");
e.preventDefault();
}
else if(!password || !confirmation) {
alert("Pls povide a password and confrim it");
e.preventDefault();
}
else if(password != confirmation) {
alert("Passwords don't match");
e.preventDefault();
}
});
});
Thanks to everyone who commented and answered my question.感谢所有评论并回答我问题的人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.