You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

笑话应用fetch数据后页面显示undefined问题求助

解决icanhazdadjoke API拉取笑话显示undefined的问题

我正在开发一个笑话应用,计划从icanhazdadjoke.com拉取笑话并展示在页面的div中,但当前代码运行后div内显示undefined,尝试使用data.jokes也无法解决问题。相关代码如下:

HTML代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dad Jokes</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" integrity="sha512-z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBreCFkKxLhei6S9CQXFEbbKuqLg0DA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="stylesheet.css">
    <script src="code.jquery.com_jquery-3.7.0.js"></script>
</head>
<body>
    <div class="container">
        <h3>Dont Laugh Challenge</h3>
        <div id="jokepad" class="jokepad">
            //joke will be here 
        </div>
        <button id="jokebtn" class="btn">Next Joke from here</button>
    </div>
    <script src="script.js"></script>
</body>
</html>

CSS代码

@import url('https://fonts.googleapis.com/css2?family=Cairo:wght@600&family=Roboto:wght@400;900&display=swap');
*{
    box-sizing: border-box;
   
}
body{
    font-family:'Roboto', sans-serif;
    margin: 0;
    display:flex;
    flex-direction: column;
    align-items: center;
    justify-content:center;
    height: 100vh;
    overflow: hidden;
    background-color: lightsalmon;
}
.container{
    background-color: pink;
    max-width: 100%;
    width:800px;
    border-radius: 10px;
    box-shadow: 0px 10px 10px violet,0px 6px 6px deeppink;
    padding: 20px 40px;
    text-align: center;
}
h3{
    opacity: 0.5;
    margin: 0;
    letter-spacing: 3px;
}
.jokepad{
    margin:20px;
    letter-spacing: 2px;
    font-size: 24px;
}
.btn{
    cursor: pointer;
    padding: 10px 20px;
    border: 0;
    border-radius: 5px;
    background-color: purple;
    color:goldenrod;
}
.btn:focus{
    outline: 0;
}
.btn:active{
    transform:scale(0.95)
}

JavaScript代码

var jokeEl = document.getElementById("jokepad");
var jokebtn = document.getElementById("jokebtn");
generateJoke();
jokebtn.addEventListener("click",generateJoke);
function generateJoke(){
    fetch("https://icanhazdadjoke.com",{headers:{
        Accept:"application/json"
    }})
    .then(function(res){ res.json()
    })
    .then(function(data){
         console.log(data);
         jokeEl.innerHTML = data;
   })

问题分析与修复

你的代码存在两个关键问题:

  1. Promise链未传递数据:第一个then回调中调用了res.json()但没有返回结果,导致下一个then接收的data为undefined。Promise链需要明确返回值才能传递解析后的数据。

  2. API字段访问错误:icanhazdadjoke.com的JSON响应中,笑话内容存储在joke字段,而非jokes或直接使用整个data对象,正确的访问方式是data.joke。

修正后的JavaScript代码

var jokeEl = document.getElementById("jokepad");
var jokebtn = document.getElementById("jokebtn");
generateJoke();
jokebtn.addEventListener("click", generateJoke);

function generateJoke() {
    fetch("https://icanhazdadjoke.com", {
        headers: {
            Accept: "application/json"
        }
    })
    .then(function(res) {
        // 返回res.json(),让下一个then拿到解析后的数据
        return res.json();
    })
    .then(function(data) {
        // 访问正确的字段data.joke
        jokeEl.innerHTML = data.joke;
    })
    // 添加错误处理,请求失败时给用户反馈
    .catch(function(error) {
        jokeEl.innerHTML = "加载笑话失败,请稍后重试。";
        console.error(error);
    });
}

额外建议

  • 你在HTML中引入了jQuery但未使用,可以考虑移除该资源,减少不必要的加载。
  • 保留catch块处理网络错误或API异常,能提升用户体验。

内容的提问来源于stack exchange,提问作者Ezz Deghedy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 16:25:35