开发者

Having problems when returning a variable using jquery

I dont know why this code doesnt work :S

function check(){
  var haySaldo=false;
  $.post("controlarSaldo.php", function(data)

 {  
        if(data>0)
          haySaldo=true;
  });

   return haySaldo;
}

开发者_运维问答Information:

data=1000

I put an alert of haySaldo inside jquery and I get "true" but outside jquery I get "false" :S

Many thx in advance!


It looks like your return statement is outside your function.

Try this

$.post("controlarSaldo.php", function(data){   
    var haySaldo=false;    
    if(data>0){
        haySaldo=true;
    }
    return haySaldo;
});


Apologies if you already understand this, but this jQuery post method is a shorthand for an AJAX requests, which means that your code will not wait for the AJAX request to complete before returning the value of haySaldo (as you have it written).

It's a little unclear what you are intending to do by calling return from inside the success method. Perhaps if you provided a little more information people could offer better suggestions.

One thing you may want to check out are jQuery's deferred objects. It would allow you to do something like this.

function check(){
  return $.post("controlarSaldo.php").success(function(data)
    {  
    if(data>0)
      return true;
    else
      return false;
    });
}

Then later on in your code you can do (untested).

check().done(function(resp){ 
  if(resp){
    // Do true thing
  }
  else{
    // Do false thing
  }
}); 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜