簡體   English   中英

如何從Facebook API返回的jsonp中獲取數據以獲取封面圖像

[英]How to fetch data from returned jsonp from Facebook API for cover image

我有一個使用用戶ID並為封面圖像調用FB圖形API的函數,該API調用是正確的,我正在獲取封面圖像url,但該URL沒有存儲在var timlineimagepath 我已經嘗試了該變量的所有可能范圍

var timelineimgpath;

function getFBTimelineImgPath(userid) {
    var URL = 'https://graph.facebook.com/' + userid + '?fields=cover';
    var path = $.ajax({
        url: URL,
        type: "GET",
        dataType: "jsonp",
        success: function (parsed_json) {
            return (timelineimgpath = parsed_json["cover"]["source"]);
        }
    }
});

我從另一個函數調用此函數,但是timelineimgpath即將到來UNDEFINED

您面臨與以下問題相同的問題:

實際上,您將無法從Ajax函數返回任何內容,因為Ajax是異步的。 認為每個Ajax調用都需要時間,並且下一條語句不會等待Ajax調用完成。

第一個解決方案:使用承諾

var timelineimgpath;

function getCover(userid) {
    return $.ajax({
        url: 'https://graph.facebook.com/' + userid + '?fields=cover',
    });
}

getCover("19292868552").done(function (data) {
    /** You have to do everything you need with your data HERE */
    timelineimgpath = data.cover.source;
    alert(timelineimgpath); // <-- this is called after
});

/** 
 * You see that the data is not available 
 * The Facebook API query has not occured yet!
 */
alert(timelineimgpath); // <-- "undefined"

的jsfiddle


第二種解決方案:使用回調

function getCover(callback, userid) {
    $.ajax({
        url: 'https://graph.facebook.com/' + userid + '?fields=cover',
        success: callback
    });
}

function doWithCover(data) {
    /** You have to do everything you need with your data HERE */
    alert(data.cover.source);
}

getCover(doWithCover, '19292868552');

的jsfiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM