freeCodeCamp Twitchtv APi 项目:AJAX 调用错误

freeCodeCamp Twitchtv APi Project: AJAX call error

我正在尝试制作一个 freeCodeCamp Intermediate Front End Development project,需要我使用 Twitchtv API。


目前,此代码出错。当我用 JSHint 分析它时,它说我不能将函数放入循环中。

代码:

$("document").ready(function() {
  var streamers = [
    "ESL_SC2",
    "OgamingSC2",
    "cretetion",
    "freecodecamp",
    "storbeck",
    "habathcx",
    "RobotCaleb",
    "noobs2ninjas"
  ];
  var htm = "";
  for (i = 0; i < streamers.length; i++) {
    var url = "https://wind-bow.gomix.me/twitch-api/channels/" + streamers[i];
    console.log(url);
    $.ajax({
      type: "GET",
      url: url,
      dataType: "json",
      success: function(data) {
        console.log("Success!");
        console.log(url);
        console.log(data);
      },
      error: function(data) {
        console.log("Error!");
      }
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


现在,当我从循环中删除函数时,会出现数据未定义的错误。

代码:

function myFunction(data) {
  console.log("Success!");
  console.log(url);
  console.log(data);
}

function myFunction2(data = null) {
  console.log("Error!");
}
$("document").ready(function() {
  var streamers = [
    "ESL_SC2",
    "OgamingSC2",
    "cretetion",
    "freecodecamp",
    "storbeck",
    "habathcx",
    "RobotCaleb",
    "noobs2ninjas"
  ];
  var htm = "";
  for (i = 0; i < streamers.length; i++) {
    var url = "https://wind-bow.gomix.me/twitch-api/channels/ESL_SC2"; //+streamers[i];
    console.log(url);
    $.ajax({
      type: "GET",
      url: url,
      dataType: "json",
      success: myFunction(data),
      error: myFunction2(data)
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


我从 here

得到 API

我想知道如何从我的代码中消除这些问题:

查看此处是您的 ajax 调用的工作示例

$("document").ready(function() {
        var streamers = [
            "ESL_SC2",
            "OgamingSC2",
            "cretetion",
            "freecodecamp",
            "storbeck",
            "habathcx",
            "RobotCaleb",
            "noobs2ninjas"
        ];
        for (i = 0; i < streamers.length; i++) {
            $.ajax({
                url: "https://wind-bow.gomix.me/twitch-api/channels/"+streamers[i],
                type: 'GET',
                dataType: 'jsonp', // added data type
                success: function(res) {
                    console.log(res);
                }
            });
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>