内部的Ajax请求for循环

时间:2017-10-19 15:39:28

标签: jquery ajax

我设置这个for循环来遍历数组,这样我就可以遍历每个通道来获取每个值的对象但是当我分析代码时,我得到一个错误,我不应该在循环中创建函数。是否有更合适的方法来获得此功能而无需在循环内创建函数?

以下是codepen的链接:https://codepen.io/Na-Ya/pen/EwrOYY

$(document).ready(function(){

var channels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];

for (var i=0; i<channels.length; i++){  

 $.ajax({
method: "get",
url:"https://wind-bow.gomix.me/twitch-api/streams/" + channels[i],
dataType: "jsonp",
success: function(data){    
// if statement for offline channels 
 if (data.stream === null){

  //sets offlineName to the channel name
  var offlineName = data._links.channel.replace("https://api.twitch.tv/kraken/channels/", "").toLowerCase();

  $("#offline").append("<div class='row'>" + "<div class='col m-2'>" + "<h3>" + offlineName + ": Offline" + "</h3>" + "</div>" + "</div>");    
} 
else if (data.stream.channel !== null){

var channelName = data.stream.channel.display_name;
var channelStatus = data.stream.channel.status;
var channelLogo= data.stream.channel.logo;
var channelUrl = data.stream.channel.url;
var channelGame = data.stream.channel.game;  
  $("#online").append("<div class='row'>" + "<div class='col'>" + "<img class='mx-auto' src='" + channelLogo + "' alt='Logo'>" + "<h3>" + channelName + "</h3>" + "<a href='" + channelUrl + "'>" + "<p>" + channelGame + ": " + channelStatus + "</p>" + "</a>" + "</div>" + "</div>");            
}         
 }, //closes out success function   
});  //closes out ajax request
};//closes out for loop   
}); //closes out document ready

1 个答案:

答案 0 :(得分:0)

在这种情况下,可以通过在循环外部将命名的函数写入循环并使用名称将函数指定为成功处理程序来避免循环函数:

$(document).ready(function() {
    var channels = ...;
    function successHandler(data) {
        ...
    }
    for (var i=0; i<channels.length; i++) {
        $.ajax({
            'method': 'get',
            'url': 'https://wind-bow.gomix.me/twitch-api/streams/' + channels[i],
            'dataType': 'jsonp',
            'success': successHandler
        });
    }
});

那应该回答这个问题。

此外,如上所述,sussess处理程序缺少无条件else,因此如果data.stream === nulldata.stream.channel === null,则不会构建/显示HTML。这种情况可能永远不会发生,但你应该采取防御措施 - 总是假设最坏的情况。

改为考虑:

if (data.stream && data.stream.channel) {
    // build HTML for the Channel 
} else {
    // build HTML for offlineName 
}