问题描述
现在尝试让它工作一段时间:
Trying to get this to work for sometime now:
<input id="usr_login_attp" value="ok" />
function check_for_acc() {
$("#usr_login_attp").val("ok");
jQuery.ajax({
url: "http://localhost:3000/login/validate_user/",
type: 'POST',
dataType: 'json',
data: {'email':$('#user_email').val(), 'password':$('#user_password').val(), 'authenticity_token': jQuery('input[name="authenticity_token"]').val()},
error: function(xhr_data) {
//sdfsd
},
success: function(xhr_data) {
$("#usr_login_attp").val(xhr_data.status);
}
});
}
check_for_acc();
if ($("#usr_login_attp").val() == "fail") {
err++;
errStr += "Email or Password Was Not Recognized<br />";
}
ajax函数正在更新 $(# usr_login_attp)
带ok或fail的字段,这部分工作正常,但是当我调用 check_for_acc()
时,以下内容如下if语句是否无法每次都通过,无论 $(#usr_login_attp)
的实际值是什么?
The ajax function is updating the $("#usr_login_attp")
field with either "ok" or "fail", this part is working ok, however when I call check_for_acc()
, the following if statement fails to pass everytime, regardless of what the actual value of $("#usr_login_attp")
is?
这让我疯了,谁能看到我在这里做错了什么?
This is driving me nuts, can anyone see what I'm doing wrong here?
推荐答案
是的!您认为 success
处理程序将在脚本的其余部分执行之前执行。这几乎肯定是不正确的。
Yep! You're thinking that the success
handler will execute before the rest of your script does. That's almost certainly incorrect.
登录成功/失败的处理需要在回调中进行。一旦调用 check_for_acc()
,它就会进行Ajax调用 - 但是在Ajax调用完成之前不会调用回调。与此同时,您的代码会快速运行。
The processing of the login success/failure needs to happen within the callback. Once you call check_for_acc()
, it makes the Ajax call--but the callback doesn't get called until the Ajax call completes. Meanwhile, your code runs merrily along.
或者,您可以使用用于包含一些跳箍的功能。
Alternatively, you could use the jQuery.when()
function to wrap up some of that hoop jumping for you.
这篇关于如何通过JQuery / Ajax验证用户名/密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!