weixin_33726318 2017-10-19 15:39 采纳率: 0%
浏览 50

Ajax请求内循环

I set up this for loop to iterate through the array so that I could cycle through each channel to get an object for each value but when I analyze the code I get an error that I should not create functions inside a loop. Is there a more proper way to get this functionality without creating the function inside the loop?

Here is a link to the 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条回答 默认 最新

  • weixin_33701617 2017-10-19 16:17
    关注

    In this case, function in loop can be avoided by writing it, as a named function, outside the loop and using the name to specify the function as the success handler:

    $(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
            });
        }
    });
    

    That should anwer the question.

    In addition, as written the sussess handler lacks an unconditional else, therefore if data.stream === null and data.stream.channel === null, no HTML will be built/displayed. That may never happen but you should program defensively - always assume the worst.

    Consider instead :

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog