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条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 使用自定义的类型代替内置类型可行吗
      • ¥15 关于STM32的SPI和ENDAT接口编码器通信的问题
      • ¥15 关于#pdfbox#生成的PDF文件正常,转图片中文乱码的问题,如何解决?
      • ¥15 ADS中有关DAC控件的使用问题
      • ¥15 win11如何运行geoserver
      • ¥15 审稿意见请教-用ERNIE进行小样本分类的对比实验问题
      • ¥15 gem5搭建arm v8
      • ¥15 安卓时间管理APP,怎么做
      • ¥15 这段有什么bug 为什么总报错
      • ¥15 Intel Realsense深度相机(D415/D435)拍摄梯子获取梯子点云