【发布时间】:2014-03-19 23:10:33
【问题描述】:
我有一个登录表单,当用户单击提交按钮时,我有一个主函数,我调用它来决定页面是否应该迁移。在 main 函数中,我调用了另外两个函数:一个检查用户名和密码字段是否为空,第二个函数有一个 ajax 来检查用户名和密码的组合是否正确:问题是带有 ajax 的函数无法正常工作,因为主函数不会等待带有 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>
非常感谢您的帮助
【问题讨论】:
-
如果要同步,请改用 .ajax,并传递 async:false。