在ajax调用jQuery之外传递数据

bla*_*bit 4 javascript ajax jquery vimeo

我从API获取vimeo缩略图,我正在使用jQuery函数将数据附加到dom.

我正在尝试访问ajax之外的thumb_url,所以我可以将它返回给jQuery,但它不起作用.

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"/>');

});
Run Code Online (Sandbox Code Playgroud)

小提琴:http://jsfiddle.net/gyQS4/2/ 求助?

Jos*_*eam 11

由于AJAX调用是异步的,因此您无法以您尝试的方式返回和访问thumb_url.

换句话说,因为您的AJAX调用可以随时获取数据(可能需要1秒;可能需要10秒),其余代码(包括return语句)将同步执行,即在服务器甚至有一个有机会回应数据.

在这些情况下使用的常见设计解决方案是执行要在回调函数内执行的任何内容.

你可以做类似的事情:

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);

}
Run Code Online (Sandbox Code Playgroud)