[英]How to keep “response” out of FB.api
我只是在嘗試FB JS api,想知道是否或如何仍可以使用FB.api中的“響應”。 例如:
var picture;
FB.api('/me/picture?width=180&height=180', function (response) {
picture = response.data.url;
console.log(picture);
});
alert(picture);
上面的代碼將在警報窗口中顯示“未定義”。
有沒有辦法在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
。
這是其他一些選擇
/me
。 實現第二種方法
/me/address
和/me/picture
/。 請參閱: https : //github.com/kriskowal/q或https://api.jquery.com/category/deferred-object/以開始使用 這是完成任務的最佳方法(不需要其他回調)
FB.api('/me', {fields: ['first_name', 'last_name', 'picture', 'address']}, function(response) {
// response will now have everything you need
console.log(response);
});
我最初沒有給出此答案,因為這似乎不是問題的主題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.