我正在尝试调用两个不同的API。我的想法是,当你点击底部时,一个随机的笑话会出现在屏幕上。我创建了两个不同的函数来获取这两个不同的API。然后,我使用Math.random()获得一个随机数。如果随机数大于50,则执行一个函数,否则执行另一个函数。我的问题是,来自Chuck Norris API的API数据总是返回Undefined,我正在努力找出错误所在。
这是我的JS代码:
const button = document.getElementById("button");
const joke = document.getElementById("joke-content");
const url = " https://icanhazdadjoke.com/";
const urlChuck = "https://api.chucknorris.io/jokes/random";
button.addEventListener("click", getJoke = () => {
const randomNumber = 100 * Math.random();
return randomNumber > 50 ? getDadJoke() : getChuckJoke();
}
);
const getDadJoke = () => {
fetch(url, {
headers: {
"Accept": "application/json"
}
}).then(response => response.json())
.then(data => joke.innerHTML = data.joke)
}
const getChuckJoke = () => {
fetch(urlChuck, {
headers: {
"Accept": "application/json"
}
}).then(response => response.json())
.then(data => joke.innerHTML = data.joke)
}发布于 2021-05-20 15:43:35
对于Chuck Norris的笑话,你指的是data.joke,但它应该是data.value
const getChuckJoke = () => {
fetch(urlChuck, {
headers: {
"Accept": "application/json"
}
}).then(response => response.json())
.then(data => joke.innerHTML = data.value)
}https://stackoverflow.com/questions/67615970
复制相似问题