我正在使用一个获取用户ID并为封面图像调用FB图形API的函数,API调用是正确的我获取了封面图片网址,但该网址未存储在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
。
答案 0 :(得分:1)
您遇到的问题与以下相同:
实际上,您将无法从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"
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');