admin管理员组文章数量:1316561
I'm getting vimeo thumbnails from the API and I'm using a jQuery function to append the data to the dom.
I'm trying to access thumb_url outside ajax, so I can return it to jQuery, but it doesn't work.
function getThumb(vimeoVideoID) {
var thumb_url;
$.ajax({
type: 'GET',
url: '/' + vimeoVideoID + '.json',
jsonp: 'callback',
dataType: 'jsonp',
success: function (data) {
console.log(data[0].thumbnail_large);
thumb_url = data[0].thumbnail_large;
}
});
return thumb_url;
}
$('.video').each(function () {
var thumb_url = getThumb(this.id);
$(this).append('<img src="' + thumb_url + '" class="video_preview"/>');
});
Fiddle: / help?
I'm getting vimeo thumbnails from the API and I'm using a jQuery function to append the data to the dom.
I'm trying to access thumb_url outside ajax, so I can return it to jQuery, but it doesn't work.
function getThumb(vimeoVideoID) {
var thumb_url;
$.ajax({
type: 'GET',
url: 'http://vimeo.com/api/v2/video/' + vimeoVideoID + '.json',
jsonp: 'callback',
dataType: 'jsonp',
success: function (data) {
console.log(data[0].thumbnail_large);
thumb_url = data[0].thumbnail_large;
}
});
return thumb_url;
}
$('.video').each(function () {
var thumb_url = getThumb(this.id);
$(this).append('<img src="' + thumb_url + '" class="video_preview"/>');
});
Fiddle: http://jsfiddle.net/gyQS4/2/ help?
Share Improve this question asked Jan 10, 2014 at 18:59 black_rabbitblack_rabbit 2772 gold badges3 silver badges10 bronze badges 1- possible duplicate of How to return AJAX response Text? – Quentin Commented Jan 10, 2014 at 19:01
1 Answer
Reset to default 17Because AJAX calls are asynchronous, you cannot return and access thumb_url the way that you're trying to.
In other words, because your AJAX call can get data at any time (it could take 1 second; it could take 10 seconds), the rest of the code (including the return statement) will execute synchronously, i.e. before the server even has a chance to respond with data.
A common design solution used in these situations is to execute whatever you want to execute inside of a callback function.
You could do something similar to this:
success: function (data) {
console.log(data[0].thumbnail_large);
thumb_url = data[0].thumbnail_large;
//utilize your callback function
doSomething(thumb_url);
}
/* then, somewhere else in the code */
//this is your callback function
function doSomething(param) {
//do something with your parameter
console.log(param);
}
本文标签: javascriptPassing data outside ajax callJQueryStack Overflow
版权声明:本文标题:javascript - Passing data outside ajax call, jQuery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739262144a2155421.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论