I have a list of facebook user id numbers from an xml response and all I want to do is write html that places their picture next to their name. Unfortunately I am having a strange problem:
var friendList = "";
$(xml).find("id").each(function ()
{
var tId = $(this).text();
var t开发者_JS百科Url = "/" + tId;
var perName = "";
FB.api(tUrl, function(response) {
perName += response.name;
});
alert(perName);
friendList += "<div class=\"picSpacer\"><img src=\"https://graph.facebook.com/"+tId+"/picture/?type=large\" class=\"friendDIV\" /><div class=\"nameBox\">"+perName+"</div></div>";
});
With this code it works, but if I remove the alert it does not work. The alert pops up undefined. It's as if the string perName has to be accessed once before it actually contains the user's name. I don't understand how this can be.
it's simple. FB.api() performs an asynchronous request, when it's finished
function(response) {
//do entire DOM manipulation here
}
gets called. Now alert() delays execution long enough, so that that callback gets calland and perName gets defined.
Just move your DOM manipulation code into the callback to make sure you actually have the response.
精彩评论