【发布时间】:2015-12-10 20:22:10
【问题描述】:
我正在使用 API 并设法让 .ajax 函数正常工作。现在,我需要在 .ajax 函数之外使用来自 API 的信息。为此,我正在尝试使用 jQuery 的 .done 函数,但它不起作用。我查看了一些类似问题的解决方案,但我没有运气。我尝试了使用和不使用 $.when 函数,但都不起作用。
//create user prototype
function user(name,logo,status,streamLink,streamViews,streamGame){
this.name = name;
this.logo = logo;
this.status = status;
this.streamLink = streamLink;
this.streamViews = streamViews;
this.streamGame = streamGame;
this.getUserInfo = function(userName) {
return $.ajax({
dataType: "jsonp",
data:{},
url:'https://api.twitch.tv/kraken/users/'+userName+'?callback=?',
success:function(data){
this.name = data.display_name;
this.logo = data.logo;
this.bio = data.bio;
$('.test').html(this.logo);
}
})
}
}
//create user for each stream
var freeCodeCamp = new user('freeCodeCamp');
var medrybw = new user('medrybw');
//call getUserInfo function
freeCodeCamp.getUserInfo('freeCodeCamp');
medrybw.getUserInfo('medrybw');
//display medrybw status (test) - not working!
when(medrybw.getUserInfo()).done(function(data){
alert('test');
$('.test2').html(medrybw.bio);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test"></div>
<br>
<br>
<div class="test2"></div>
不工作的部分是最后一个功能。 如果我删除 $.when 部分,我会得到“测试”警报工作正常,但不是另一行。使用 $.when,两条线都不会运行。我真的很困惑。
【问题讨论】:
-
你没有
$.when。你只有when。 -
只有在使用 多个 承诺时才需要使用
$.when。$.when(x)与x相同。问题在于您的成功回调中的this不指向该对象(并且when(您使用的)不存在这一事实)。见stackoverflow.com/q/20279484/218196 -
this不是你想的那样,在 ajax 的成功中。
标签: javascript jquery ajax asynchronous