【问题标题】:Passing data outside ajax call, jQuery在ajax调用之外传递数据,jQuery
【发布时间】:2014-01-10 18:59:13
【问题描述】:

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

});

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

【问题讨论】:

标签: javascript jquery ajax vimeo


【解决方案1】:

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

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

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

你可以做类似的事情:

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

}

【讨论】:

  • 或类似,使用 promise 接口的 done() 方法:jsfiddle.net/xSKc8
  • 它记录实际图像,但是当我检查 dom 时,我仍然得到 img src="undefined" 。看起来还是 var thumb_url 最后没有返回 jsfiddle.net/gyQS4/3
  • 这里不能使用return语句。你必须在回调函数中做所有事情。 See this jsfiddle
猜你喜欢
  • 2013-12-15
  • 1970-01-01
  • 1970-01-01
  • 2017-02-12
  • 1970-01-01
  • 2021-11-11
  • 1970-01-01
  • 1970-01-01
  • 2014-03-25
相关资源
最近更新 更多