javascript 在 ajax 调用之外传递数据,jQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21052258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:55:59  来源:igfitidea点击:

Passing data outside ajax call, jQuery

javascriptjqueryajaxvimeo

提问by black_rabbit

I'm getting vimeo thumbnails from the API and I'm using a jQuery function to append the data to the dom.

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

I'm trying to access thumb_urloutside ajax, so I can return it to jQuery, but it doesn't work.

我正在尝试访问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"/>');

});

Fiddle: http://jsfiddle.net/gyQS4/2/help?

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

回答by Josh Beam

Because AJAX calls are asynchronous, you cannot return and access thumb_urlthe way that you're trying to.

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

In other words, because your AJAX call can get dataat any time (it could take 1 second; it could take 10 seconds), the rest of the code (including the returnstatement) will execute synchronously, i.e. before the server even has a chance to respond with data.

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

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

}