Greetings,
I'm working with a JavaScript object that is defined like so:
var ytVideoData = new Object();
I then assign a value to it inside of a jQuery .ajax():
$.ajax({
type: "GET",
url: "xmlproxy.php?url="+ytId+"&mode=native",
success: function(data) {
ytVideoData.thumbnail = $(data).find("media\\:thumbnail[yt\\:name='default']")开发者_JAVA技巧.attr("url"); // default thumbnail image
}
});
In another function, I want to access the thumbnail property I just set. However, when I do:
function addPlaylistItem(tumblrUser, videoData) {
console.log(videoData.thumbnail);
}
All I get in the console is "undefined". When I do:
console.log(videoData);
I get the entire object logged to the console and can see the thumbnail property properly set inside of the object like so:
http://mp3.deceast.com/js-objectissue.jpg
After trying several different methods I just can't seem to get it work. How do I access this object property?
A callback via ajax is asychronous. WHich means you can't tell when it will run the success function.
The order that is probably happening is
$.ajax
addPlaylistItem // undefined
success // defined
Try calling the function in the success postback
success: function(data) {
ytVideoData.thumbnail = $(data).find("media\\:thumbnail[yt\\:name='default']").attr("url"); // default thumbnail image
addPlaylistItem(getTumblrUser(), ytVideoData);
}
精彩评论