gpt4 book ai didi

jquery - 如何让函数等待jquery ajax完成

转载 作者:行者123 更新时间:2023-12-01 07:57:58 26 4
gpt4 key购买 nike

我有一个登录表单,当用户单击提交按钮时,我有一个主函数,我调用它来决定页面是否应该迁移。在主函数中,我调用了另外两个函数:一个用于检查用户名和密码字段是否为空,第二个函数有一个ajax,用于检查用户名和密码的组合是否正确:问题是带有ajax的函数无法正常工作,因为 main 函数不等待带有 ajax 的内部函数完成(异步):这是示例代码:

<h3 id="myerror" style="display:none;">Invalid username or password</h3>

<form action="mylogin.php" onSubmit="return mymain()">
username<input type="text" id="myuname">
password:<input type="password" id="mypass">
</form>

//and the script

<script>

function mymain() {
if (is_not_empty() && is_in_database()) {
return true;
} else {
return false;
}
}

function is_not_empty() {
var uname = $("#myuname").val();
var pass = $("#mypass").val();
if (uname == "" && pass == "") {
$("#myerror").css("display", "block");
return false;
} else {
return true;
}
}

var a;

function isthere() {

var uname = $("#myuname").val();
var pass = $("#mypass").val();

//the ajax php below returns either isthere or notthere with reference to the username
and password combination.

$.post("http://localhost/passtester/pass1.php", {
username: uname,
password: pass
}, function (feedbak) {
a = feedbak;
});
if (a == "isthere") return true;
if (a == "notthere") return false;
}
</script>

我非常感谢您的帮助

最佳答案

您无法从异步方法返回值,而是需要使用回调方法,例如

function mymain() {
if (is_not_empty()) {
is_in_database(function (isthere) {
if (isthere) {
$('form').submit();
}
})
}
return false;
}

function is_not_empty() {
var uname = $("#myuname").val();
var pass = $("#mypass").val();
if (uname == "" && pass == "") {
$("#myerror").css("display", "block");
return false;
} else {
return true;
}
}

function is_in_database(callback) {

var uname = $("#myuname").val();
var pass = $("#mypass").val();

//the ajax php below returns either isthere or notthere with reference to the username and password combination.

$.post("http://localhost/passtester/pass1.php", {
username: uname,
password: pass
}, function (feedbak) {
callback(feedbak == "isthere")
});
}

关于jquery - 如何让函数等待jquery ajax完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22520126/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com