在ajax调用之外传递数据,jQuery [英] Passing data outside ajax call, jQuery
问题描述
我从API获取vimeo缩略图,并且正在使用jQuery函数将数据附加到dom.
I'm getting vimeo thumbnails from the API and I'm using a jQuery function to append the data to the dom.
我正在尝试在ajax外部访问 thumb_url ,因此我可以将其返回给jQuery,但这是行不通的.
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"/>');
});
小提琴: http://jsfiddle.net/gyQS4/2/ 帮助吗?
推荐答案
由于AJAX调用是异步,因此您无法返回并访问 thumb_url
Because AJAX calls are asynchronous, you cannot return and access thumb_url the way that you're trying to.
换句话说,由于您的AJAX调用可以随时获取数据(可能需要1秒;可能需要10秒),因此其余代码(包括 return 语句)将同步执行,即在服务器甚至没有机会响应数据之前.
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.
您可以执行以下操作:
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);
}
这篇关于在ajax调用之外传递数据,jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!