使用ajax调用无法获得正确的索引结果

时间:2016-09-29 06:43:32

标签: javascript jquery ajax

我试图通过变量showindex迭代'streamers'数组但是失败了,它只显示数组的第一个元素“monstercat”和最后一个元素“amazhs”,在displayResult函数中使用chrome和showindex中的调试是0和9,无法弄清楚为什么,有什么帮助吗?谢谢!

var streamers = ['monstercat', 'sivhd', 'cryaotic', 'nightblue3', 'picoca_lol', 'freecodecamp', 'trick2g', 'riotgamesbrazil', 'riotgames', 'amazhs'];
$(document).ready(function() {
  var logo = "";
  var channelName = "";
  var showindex = 0;

  streamers.forEach(function(streamer, index) {
    showindex = index;
    $.ajax({
      type: 'GET',
      jsonp: "callback",
      url: 'https://api.twitch.tv/kraken/streams/' + streamer,
      headers: {
        'Client-ID': 'd50b88uvtwlhdfrqi3vj3k1hm3izkyx'
      },
      success: displayResult
    });
  });

  function displayResult(data) {
    var outstring = "";
    if (data.stream !== null) {
      channelName = data.stream.channel.display_name;
      logo = data.stream.channel.logo;
    } else {
      logo = "https://placeholdit.imgix.net/~text?txtsize=6&txt=50%C3%9750&w=50&h=50";
      channelName = streamers[showindex];
    }
    outstring +=
      "<li class='streamer'>" +
      "<img class='streamer-icon' src='" + logo + "'/>" +
      "<p class='streamer-name'>" +
      "<a href='http://twitch.tv/" + channelName + "' target='_blank'>" + channelName + "</a></p>" +
      "<span class='streamer-status'>" +
      "<i class='fa fa-exclamation'></i></span></li>"
    $("#showBox").append(outstring);
  }
});
ul {
  padding: 0;
  margin: 0;
}

.tab-content {
  border: 1px solid #ddd;
  border-top: none;
}

.streamer {
  list-style-type: none;
  padding: 10px;
}

.streamer-icon {
  width: 50px;
}

.streamer-name {
  display: inline-block;
  margin-left: 10px;
}

.streamer-status {
  float: right;
  padding-top: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="row col-md-4 col-md-offset-4">
    <ul class="nav nav-tabs" role="tablist">
      <li class="active"><a href="#all" aria-controls="all" role="tab" data-toggle="tab">all</a>
      </li>
      <li><a href="#online" aria-controls="online" role="tab" data-toggle="tab">online</a>
      </li>
      <li><a href="#offline" aria-controls="offline" role="tab" data-toggle="tab">offline</a>
      </li>
    </ul>
    <div class="tab-content">
      <div class="tab-pane active" id="all">
        <ul id="showBox">
        </ul>
      </div>
      <div class="tab-pane" id="online">
        <ul></ul>
      </div>
      <div class="tab-pane" id="offline">
        <ul></ul>
      </div>
    </div>
  </div>
</div>

2 个答案:

答案 0 :(得分:1)

这是因为这些呼叫都是在同一时间发生的,所以立即showindex = 9这样可以在displayResult中进行增量虽然它仍然可能出错(但它不太可能)。

你可能完全改变你的代码,使其使用更安全的承诺。

&#13;
&#13;
var streamers = ['monstercat', 'sivhd', 'cryaotic', 'nightblue3', 'picoca_lol', 'freecodecamp', 'trick2g', 'riotgamesbrazil', 'riotgames', 'amazhs'];
$(document).ready(function() {
  var logo = "";
  var channelName = "";
  var showindex = 0;

  streamers.forEach(function(streamer, index) {
    $.ajax({
      type: 'GET',
      jsonp: "callback",
      url: 'https://api.twitch.tv/kraken/streams/' + streamer,
      headers: {
        'Client-ID': 'd50b88uvtwlhdfrqi3vj3k1hm3izkyx'
      },
      success: displayResult
    });
  });

  function displayResult(data) {
    var outstring = "";
    if (data.stream !== null) {
      channelName = data.stream.channel.display_name;
      logo = data.stream.channel.logo;
    } else {
      logo = "https://placeholdit.imgix.net/~text?txtsize=6&txt=50%C3%9750&w=50&h=50";
      channelName = streamers[showindex];
    }
    outstring +=
      "<li class='streamer'>" +
      "<img class='streamer-icon' src='" + logo + "'/>" +
      "<p class='streamer-name'>" +
      "<a href='http://twitch.tv/" + channelName + "' target='_blank'>" + channelName + "</a></p>" +
      "<span class='streamer-status'>" +
      "<i class='fa fa-exclamation'></i></span></li>"
    $("#showBox").append(outstring);
    showindex++;
  }
});
&#13;
ul {
  padding: 0;
  margin: 0;
}
.tab-content {
  border: 1px solid #ddd;
  border-top: none;
}
.streamer {
  list-style-type: none;
  padding: 10px;
}
.streamer-icon {
  width: 50px;
}
.streamer-name {
  display: inline-block;
  margin-left: 10px;
}
.streamer-status {
  float: right;
  padding-top: 15px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="row col-md-4 col-md-offset-4">
    <ul class="nav nav-tabs" role="tablist">
      <li class="active"><a href="#all" aria-controls="all" role="tab" data-toggle="tab">all</a>
      </li>
      <li><a href="#online" aria-controls="online" role="tab" data-toggle="tab">online</a>
      </li>
      <li><a href="#offline" aria-controls="offline" role="tab" data-toggle="tab">offline</a>
      </li>
    </ul>
    <div class="tab-content">
      <div class="tab-pane active" id="all">
        <ul id="showBox">
        </ul>
      </div>
      <div class="tab-pane" id="online">
        <ul></ul>
      </div>
      <div class="tab-pane" id="offline">
        <ul></ul>
      </div>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

这是另一种方法,它不会使用foreach,而是以另一种方式遍历数组。这种方式有点慢,但意味着它没有超越自己(你实际上可以看到每一个弹出)

&#13;
&#13;
var streamers = ['monstercat', 'sivhd', 'cryaotic', 'nightblue3', 'picoca_lol', 'freecodecamp', 'trick2g', 'riotgamesbrazil', 'riotgames', 'amazhs'];
$(document).ready(function() {
  var logo = "";
  var channelName = "";
  var showindex = 0;

  //Work out if there are any streamers left in the array
  function calcStreamers() {
    if (showindex < (streamers.length - 1)) {
      //if there are add 1 and go get it
      showindex++;
      streamersGet();
    } else {
      //if not just stop
      return false
    }
  };

  //The get function
  function streamersGet() {
    $.ajax({
      type: 'GET',
      jsonp: "callback",
      url: 'https://api.twitch.tv/kraken/streams/' + streamers[showindex],
      headers: {
        'Client-ID': 'd50b88uvtwlhdfrqi3vj3k1hm3izkyx'
      },
      success: displayResult
    });
  };

  function displayResult(data) {
    var outstring = "";
    if (data.stream !== null) {
      channelName = data.stream.channel.display_name;
      logo = data.stream.channel.logo;
    } else {
      logo = "https://placeholdit.imgix.net/~text?txtsize=6&txt=50%C3%9750&w=50&h=50";
      channelName = streamers[showindex];
    }
    outstring +=
      "<li class='streamer'>" +
      "<img class='streamer-icon' src='" + logo + "'/>" +
      "<p class='streamer-name'>" +
      "<a href='http://twitch.tv/" + channelName + "' target='_blank'>" + channelName + "</a></p>" +
      "<span class='streamer-status'>" +
      "<i class='fa fa-exclamation'></i></span></li>"
    $("#showBox").append(outstring);
    //Once the data has been added to the page go and check if there are more to add
    calcStreamers();
  }
  //Initally start by getting the first result
  streamersGet();
});
&#13;
ul {
  padding: 0;
  margin: 0;
}
.tab-content {
  border: 1px solid #ddd;
  border-top: none;
}
.streamer {
  list-style-type: none;
  padding: 10px;
}
.streamer-icon {
  width: 50px;
}
.streamer-name {
  display: inline-block;
  margin-left: 10px;
}
.streamer-status {
  float: right;
  padding-top: 15px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="row col-md-4 col-md-offset-4">
    <ul class="nav nav-tabs" role="tablist">
      <li class="active"><a href="#all" aria-controls="all" role="tab" data-toggle="tab">all</a>
      </li>
      <li><a href="#online" aria-controls="online" role="tab" data-toggle="tab">online</a>
      </li>
      <li><a href="#offline" aria-controls="offline" role="tab" data-toggle="tab">offline</a>
      </li>
    </ul>
    <div class="tab-content">
      <div class="tab-pane active" id="all">
        <ul id="showBox">
        </ul>
      </div>
      <div class="tab-pane" id="online">
        <ul></ul>
      </div>
      <div class="tab-pane" id="offline">
        <ul></ul>
      </div>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您想要正确迭代数组吗?

var streamers = ['monstercat', 'sivhd', 'cryaotic', 'nightblue3', 'picoca_lol', 'freecodecamp', 'trick2g', 'riotgamesbrazil', 'riotgames', 'amazhs'];
         $(document).ready(function() {
           $(streamers).each(function(index, streamer){
             console.log(streamer+" "+index);
           });
         });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>