如何点击按钮触发API请求并在浏览器中展示无特殊字符的纯文本
存在的两处问题
- ID选择器不匹配:HTML中按钮的id为
fetchdata,JavaScript代码里查询的是#fetch-data,拼写不一致导致点击事件绑定失败 - 输出内容错误:当前你将完整的JSON响应对象序列化后输出,所以会带上大括号、引号等JSON结构符号,这个API的响应结构固定为
{ type: "success", value: { id: 笑话ID, joke: "纯文本笑话内容"} },只需取value.joke字段即可得到无特殊符号的纯文本笑话
修正后的JavaScript代码
// 选择器和HTML的按钮id保持一致 const fetchDataBtn = document.querySelector("#fetchdata"); const result = document.querySelector("#result"); // 从API拉取数据并展示 async function getData() { result.innerText = "加载中...."; try { // 改用https协议避免浏览器的混合内容拦截 const res = await fetch("https://api.icndb.com/jokes/random"); const jsonResult = await res.json(); // 直接输出纯文本笑话内容 result.innerText = jsonResult.value.joke; } catch (error) { result.innerText = "获取笑话失败,请稍后重试"; console.log(error); } } // 绑定按钮点击事件 fetchDataBtn.addEventListener("click", getData);
HTML代码无需修改,直接使用你现有代码即可
内容的提问来源于stack exchange,提问作者Ren
相关产品推荐
相关产品推荐

