如何获取数据从返回json从Facebook API的封面图片

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

本文关键字:API Facebook 封面 json 返回 获取 数据 何获取      更新时间:2023-09-26

我有一个函数,它正在获取用户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

你面临的问题和别人一样:

    jQuery: ajax调用成功后返回数据
  • 如何从异步调用返回响应?

实际上,您将无法从Ajax函数返回任何东西,因为Ajax是异步的。认为每个Ajax调用都需要时间,并且下一个语句不需要等待Ajax调用完成。

第一种解决方案:使用promise

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