我正在尝试制作一个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!");
}
});
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
现在当我从循环中删除函数时,它会给出一个错误,即没有定义数据。
代码:
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)
});
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
我从here
获得了API我想知道如何从我的代码中删除这些问题:
答案 0 :(得分:0)
请参阅此处是您的ajax调用的工作示例
.vertical-center-table-cell {
display: table-cell;
border: 1px solid #ddd;
height: 100px;
vertical-align: middle;
}
$("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);
}
});
}
});