我声明了两个带有名称,链接和页面属性的对象。在从Twitch API接收数据后,我向我的对象添加了一个属性状态,该属性在函数内部工作,但是离开它我不能再访问状态属性了。我甚至尝试使用getApi设置status属性以返回状态为streamer0.status = getApi();但它也不起作用。
var streamer0={name:"freecodecamp"};
streamer0.link='https://api.twitch.tv/kraken/streams/'+streamer0.name; streamer0.page='https://www.twitch.tv/'+streamer0.name;
var streamer1={name:"famasfordemacia"};
streamer1.link='https://api.twitch.tv/kraken/streams/'+streamer1.name;
streamer1.page='https://www.twitch.tv/'+streamer1.name;
var link="";
$(document).ready(function(){
load();
function load(){
for(var i=0;i<2;i++)
{
switch(i){
case 0:{
link=streamer0.link;
getApi(streamer0);
console.log(streamer0.status) //it does not work
break;
}
case 1:{
link=streamer1.link;
getApi(streamer1);
console.log(streamer1.status) //it does not work
break;
}
}
}
function getApi(x){
$.ajax({
type: 'GET',
url: link,
headers: {
'Client-ID': 'xxxxxxxxxxxxx'
},
success: function(data) {
if(data["stream"]==null)
{
x.status="offline";
console.log(x.status)//works
}
else
{
x.status="online";
}
}
});
}
});
答案 0 :(得分:1)
您正在使用Ajax,它是异步的,因此您有三个选择:
1 - 将所有代码放入成功回调中,这将是一个很大的失误。
function getApi(x) {
$.ajax({
type: 'GET',
url: link,
headers: {
'Client-ID': 'xxxxxxxxxxxxx'
},
success: function (data) {
// ALL YOUR CODE IN HERE
}
});
}
2 - 使用回调函数:
function getApi(x, callback) {
$.ajax({
type: 'GET',
url: link,
headers: {
'Client-ID': 'xxxxxxxxxxxxx'
},
success: function (data) {
// PASS YOUR DATA YOU THE CALL BACK
callback(data);
}
});
}
// THEN USE IT IN THE LOAD FUNCTION AS THE FOLLOWING
function load(){
for(var i=0;i<2;i++)
{
switch(i){
case 0:{
link=streamer0.link;
getApi(streamer0,function(data){
console.log(data.status) //it does not work
});
break;
}
case 1:{
link=streamer1.link;
getApi(streamer1,function(data){
console.log(data.status) //it does not work
});
break;
}
}
}
3 - 正在使用Promise(https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)。
答案 1 :(得分:0)
这是一个异步调用,所以你需要等到调用完成,
function getApi(x) {
return $.ajax({
type: 'GET',
url: link,
headers: {
'Client-ID': 'xxxxxxxxxxxxx' }});
case 0:{
link=streamer0.link;
getApi(streamer0).success(function(data){
if(data["stream"]==null)
{
streamer0.status="offline";
console.log(streamer0.status)//works
}
else
{
streamer0.status="online";
}
}
console.log(streamer0.status) //it does not work
});
break;
}
希望它可以帮助你,:)