以下是我正在使用的内容,我对其进行了简化:
if (response.authResponse) {
FB.api('/me', function(response) {
response.id;
user_id = response.id; // I thought I could at least access it below if it was defined globally...
});
var friend_list = [];
FB.api('/me/friends', function(response) {
$.each(response.data,function(index,friend) {
friend_list.push(friend.id);
});
user_friend_list = friend_list.toString();
});
alert("user id:"+user_id+"friend list:"+user_friend_list); // Here is where I would like these two variables to show up
} else {
//user cancelled login or did not grant authorization
}
可能是出于一些明显的原因(由于我的javascript和jquery不好)我无法捕获变量。如果你提供答案,请解释一下,这样我就可以获得洞察力和学习。
答案 0 :(得分:1)
试试这个。
if (response.authResponse) {
FB.api('/me', function(data) {
var user_id = data.id;
FB.api('/me/friends', function(response) {
var friend_list = [];
for (i = 0; i < response.data.length; i++) {
friend_list.push(response.data[i].id);
}
//user_friend_list = friend_list.join(",");
alert("user id:" + user_id + "friend list:" + friend_list.join(","));
});
});
}
else {
alert("no access granted");
}
改变了一些代码。如果您对此解决方案有疑问,请发表评论。
答案 1 :(得分:0)
您可以假设这些值的唯一位置是作为第二个参数提供的回调函数。这是因为api()方法是异步的。
您可以使用以下代码结束:
if (response.authResponse) {
FB.api('/me', function (response) {
// Now first asyncrhonous call is over, let's do the second one
response.id;
user_id = response.id; // I thought I could at least access it below if it was defined globally...
var friend_list = [];
FB.api('/me/friends', function (response) {
// Now second asynchronous call is over, we have both values defined.
$.each(response.data, function (index, friend) {
friend_list.push(friend.id);
});
user_friend_list = friend_list.toString();
alert("user id:" + user_id + "friend list:" + user_friend_list); // Here is where I would like these two variables to show up
});
});
} else {
//user cancelled login or did not grant authorization
}