开发者

Strange behaviour with an ajax callback function

开发者 https://www.devze.com 2023-02-01 07:51 出处:网络
when trying set a variable from an ajax callback function I\'m getting unpredictable results: var logged_in=false;

when trying set a variable from an ajax callback function I'm getting unpredictable results:

var logged_in=false;

function check_response(response,el) {
logged_in=true; 
alert(logged_in); //outputs TRUE
}

makePOSTRequest("/is_logged.php", check_response); //when ready call check_response() with the XML response
alert(logged_i开发者_JAVA百科n); //first time outputs FALSE;
alert(logged_in); //second time outputs TRUE;
  1. I run POSTRequest to check if my user is logged_in.
  2. POSTRequest calls back the function check_response() to parse the response and set the variable logged_in to TRUE.
  3. Next when I try to use the variable logged_in it is: 1st time FALSE; then TRUE...

Do you know why such strange behaviour is happening?


Because the "makePOSTRequest" is asynchronous so the first "alert" after that method shows "false" because that is the default value of the variable set earlier and as you are calling alert so you are actually "blocking" the execution of the second alert and by that time the request finishes and "logged_in" is set true.


Is the problem the same when passing 0 or 1 in place of true or false ?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号