使用JavaScript获取图片资源及信息但无内容显示的问题排查
问题排查:XKCD漫画加载页面仅显示按钮无内容
问题概述
代码意图是从XKCD的JSON接口加载漫画信息,在页面展示标题、图片,并通过按钮加载新漫画,但目前页面仅显示按钮,点击后也无内容展示。
代码展示
JavaScript代码
// function to output the image to the page with the title and description function output(comic_info) { let article = document.createElement("article"); let h3 = document.createElement("h3"); h3.innerHTML = comic_info.title; let img = document.createElement("img"); img.src = comic_info.img; img.alt = comic_info.alt; article.appendChild(h3); article.appendChild(img); document.getElementById("comics").appendChild(article); } // fetch the info from the url about the comic async function getComic(comic_url) { const response = await fetch(comic_url); // check that fetch is successful if (response.ok) { comic_info = await response.json(); output(comic_info); } } // get a different comic's info function getNewComic() { let random_number = Math.floor(Math.random() * 1000); let comic_url = "https://xkcd.com/" + random_number + "/info.0.json"; getComic(comic_url); } // when a button is clicked, get a new comic document.getElementById("new_comic").addEventListener("click", getNewComic);
HTML代码
<body> <main> <section> <!-- div to add comic image and info to the page --> <div id="comics"> </div> <!-- button to choose new comic --> <button id="new_comic">New Comic</button> </section> </main> <footer> ©<span id="year"></span> | Project | Lesson 06 </footer> <script src="/week06/student_files/scripts/main.js"></script> <script src="/week06/w06_project.js"></script> </body>
排查与修复方案
1. 未声明变量导致的作用域错误
在getComic函数中,comic_info = await response.json();未使用let或const声明,会被解析为全局变量,在严格模式下会直接抛出错误,导致后续output函数无法执行。
修复:添加变量声明:
if (response.ok) { const comic_info = await response.json(); output(comic_info); }
2. 缺少初始加载逻辑
当前代码仅在按钮点击时触发加载,页面初始化时#comics容器为空,所以打开页面只看到按钮。若需要页面加载即显示漫画,需在脚本末尾添加初始调用:
// 页面加载完成后自动加载一次漫画 window.addEventListener('DOMContentLoaded', getNewComic);
3. 脚本路径或加载顺序问题
检查w06_project.js的路径是否正确,若路径错误,JS代码未被加载,点击按钮自然无反应。可以通过浏览器开发者工具的网络面板查看是否有404错误,或在脚本开头添加console.log('脚本已加载')验证代码是否运行。
4. 缺失请求错误处理
XKCD部分漫画编号不存在,会导致fetch返回非200状态码,当前代码未处理这种情况,点击按钮后无任何反馈。建议添加错误捕获:
async function getComic(comic_url) { try { const response = await fetch(comic_url); if (response.ok) { const comic_info = await response.json(); output(comic_info); } else { console.error('漫画不存在或请求失败,状态码:', response.status); // 可选:自动重试获取新的随机漫画 getNewComic(); } } catch (error) { console.error('网络请求出错:', error); } }
5. 可选:清空旧内容
每次加载新漫画时,#comics容器会追加新内容,若需要替换旧漫画,可在output函数开头先清空容器:
function output(comic_info) { const comicsContainer = document.getElementById("comics"); comicsContainer.innerHTML = ''; // 清空旧内容 let article = document.createElement("article"); // ... 后续代码不变 }
内容的提问来源于stack exchange,提问作者Andrew Swayze
相关产品推荐
相关产品推荐

