Javascript if(function_foo()) doesn't wait for function_foo() to complete
I have an if statement:
if(aut开发者_如何学Chenticate_session("secret_password12345")){
alert("You are authenticated");
}else{
alert("Intruder alert!");
}
and the javascript authenticate function, which makes an jQuery POST AJAX call to the server to do the actual authentication, and returns true or false:
function authenticate_session(session_id){
$.post("/auth.php",
{ action: "authenticate_session", login_id: session_id },
function(data){
if(data == "denied"){
alert("denied");
return false;
}else if(data == "accepted"){
alert("accepted");
return true;
}
},
"text");
}
However, when the if statement invokes the athentication function, it doesn't wait for the AJAX to complete, and always executes the 'else'. If I add 'return true;' into the first line of the authentication function, before the ajax, the if statement performs as expected => alert("You are authenticated").
I know that the server side is performing properly, as the alert("denied") and alert("accepted") are being called as expected (but interestingly, after the if statement alerts).
How can I make my if statement wait until the authentication function has completed?
Thanks!
It's not waiting because it's an asynchronous request by default. Set the async
option to false
for it to be synchronous. From the docs:
By default, all requests are sent asynchronous (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
i don't think you can make if statement "wait" for ajax, just move the this logic into ajax callback function (well, you actually did already : alert(denied|accepted))
It is said before. Ajax does these kind of calls asynchronous. Waiting for it will may lock your browser (not desired). So you should use a callback method to handle your data. This will keep your code responsible for doing the right stuff seperated.
function authenticate_session(session_id, callbacksuccess){
$.post("/auth.php",
{ action: "authenticate_session", login_id: session_id },
callback,
"text");
}
function callback(data) {
if (data == "denied") {
alert('denied');
} else if (data == "accepted") {
alert('accepted');
}
}
authenticate_session('secret_password12345", callback);
Thanks for all your answers.
The answer turned out to be that the return within the ajax method was returning out of the ajax method, not the authentication function.
精彩评论