如何让 "response" 远离 FB.api

How to keep "response" out of FB.api

我正在尝试 FB JS api,想知道我是否或如何仍然可以使用 FB.api 中的 "response"。例如:

var picture;
FB.api('/me/picture?width=180&height=180', function (response) {
            picture = response.data.url;
            console.log(picture);
});
alert(picture);

以上代码将在警报 window 中显示 "undefined"。

有没有办法在 FB.api 中使用 "response.data.url"?

谢谢

更新: 这是大图:我需要从 FB 用户帐户检索一些信息,例如 /me/name、/me/address/city、/me/picture.data.url 并将它们组合在一起,然后发送信息通过 AJAX 到服务器。

var name;
var city;
var picture;

FB.api('/me', function (response) {
    name = response.name;
    FB.api('/me/address', function (adrresponse) {
        city = adrresponse.city;
    }
    FB.api('/me/picture', function (imgresponse) {
        picture = imgresponse.data.url;
    }
    //since FB API is async, the following is not correct!!!
    var params = "name="+name+"&city="+city+"&picture="+picture;

    //send out through AJAX.
    var http = new XMLHttpRequest();
    http.open("POST", url, true);
}

是否有更好的方法来完成上述工作?

更新 2: 最好的方法是使用字段扩展 https://developers.facebook.com/docs/graph-api/using-graph-api/v2.3#fieldexpansion,如本题答案所示。 谢谢 德里克

问题是 picture 变量在警报触发时未填充。它只会在 FB.api 回调完成后填充。

var picture;
FB.api('/me/picture?width=180&height=180', function (response) {
            picture = response.data.url;
            // this would work correctly
            alert(picture);
});

你想用 picture 变量做什么?也许你应该调用一个函数在你的回调中对图片做一些事情:

var picture;
FB.api('/me/picture?width=180&height=180', function (response) {
            picture = response.data.url;
            doSomethingWithPicture(picture);
});

更新

实现您所追求的目标的简单方法是:

FB.api('/me', function (response) {
  var name = response.name;
  FB.api('/me/address', function (adrresponse) {
    var city = adrresponse.city;
      FB.api('/me/picture', function (imgresponse) {
         var picture = imgresponse.data.url;
         doAjax(name, city, picture);
      }
  }
}

function doAjax(name, city, picture) {
   //since FB API is async, the following is not correct!!!
   var params = "name="+name+"&city="+city+"&picture="+picture;

   //send out through AJAX.
   var http = new XMLHttpRequest();
   http.open("POST", url, true);
}

但是,这并不理想,因为您必须等待 /me/address 才能调用 /me/picture

这里有一些其他选项

  1. 您需要先致电/me
  2. 你触发两个 api 调用并在两者完成后执行代码

完成 #2 的方法

更新#2

这是完成您所追求的目标的最佳方式(不需要额外的回调)

FB.api('/me', {fields: ['first_name', 'last_name', 'picture', 'address']}, function(response) {
    // response will now have everything you need
    console.log(response);
});

我最初没有给出这个答案,因为它不是问题的主题,似乎是范围界定。