开发者

JQuery and JS variables

a little misunderstanding with JQuery and JS variables. Simple example:

function someFunc(){

   var flag = true;

    $(function(){
        $.post("/some/address/", {} ,function(data){
            if( data == false){             
                flag = false;
            }
        });
    });
   if(flag == false){
      return false;
   }    
} 

The main problem is accessibility of variable flag in Jquery functions. I always get the same flag value equal to true. How to make this done ? How to make global variable to be v开发者_JAVA百科isible for JS and JQuery ?


I don't think your problem here is one of scope, actually; I think your problem is that the post function is asynchronous. That is, it goes off to the server to get data, and runs the callback function (which updates your flag) when the data comes back (which might take a while). But meanwhile, the surrounding function keeps on going; it doesn't wait for the post to return. So the flag update happens after the outer function has returned.


You're doing two asynchronous operations:

  • $(function(){}) -- fires function when document is "ready"
  • $.post -- fires XHR request

Neither of these will return immediately, -- e.g. an XHR request takes time to complete -- this is why you're passing a callback function (so that you can do stuff upon completion).

While these operations are occurring your JS will carry on executing, which means that this:

if(flag == false){
   return false;
}

... is executed before either operation (at best, just the $.post operation) completes.


The AJAX callback only executes after you return.

Therefore, when you write if(flag == false), the post callback hasn't executed yet, so flag is still true.


At a first glance it appears that by setting flag = 'false' (with 'false' being a string) instead of flag = false as a bool, that testing for flag == false will never be true.

UPDATE

Also, your jQuery code is doing a post which will return much later than the check for flag == false. It seems you're asuming that the code is operting entirely in a linear fashion however the callback method you're setting flag == false in, will be called at a much later time.


The problem is that the callback function is called much later as AJAX is asynchronous. The $.post returns immediately and the next line executes when flag is still false.


$(function(){ ... }) and $.post("address", function() { ... }) do not block. So your callback code at ... won't be executed before the js-interpreter hits if(flag == false). It's equivalent to:

var flag = true;
doSomethingLater();
if(flag == false)
  ...

flag will always be true.

Remove $(function(){ ... }) and use the async: false option for ajax requests.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜