i have this block of code:
$(document).ready(function() {
//<![CDATA[
var who;
FB_Req开发者_JS百科uireFeatures(["Api"], function(){
var who = api.get_session().uid;
alert(who);
});
alert("the uid is: "+who);
//]]>
});
the problem:
the code outside the FB_RequireFeatures block is executing before the one inside it.
due to which the value of who
is coming out to be undefined.
what am i doing wrong?
The FB_RequireFeatures
function appears to be making an asynchronous call, so you're not doing anything wrong, that's just the way it works - the alert is called before the request comes back.
You must design your code in a way that the code that depends on the result of the FB_RequireFeatures
functions are called only after the request completes. You can call another function inside the callback, for example:
var who;
$(document).ready(function() {
FB_RequireFeatures(["Api"], function() {
who = api.get_session().uid;
doSomeOtherStuff();
});
});
function doSomeOtherStuff() {
alert("the uid is: " + who);
}
Now the doSomeOtherStuff
function is called only after the FB_RequireFeatures
function finishes, and you should do all following code inside the doSomeOtherStuff
function – which you can name to be anything you want, obviously.
I moved the who
variable out of the ready block to keep it in scope for the doSomeOtherStuff
function, and removed the var
from the inner function so that you're referencing the original variable instead of creating a new one, otherwise it's the same.
You're making a new local who
variable. Remove the var
from the place where you set who. Also, you can't reference who
until the callback to the FB_RequireFeatures function is run.
精彩评论