javascript - 如何在浏览器中显示纯文本,从 API 获取
问题描述
我曾尝试使用 JSON.parse 和 JSON.stringify,但不确定如何在浏览器中显示没有特殊字符的纯文本,使用按钮,从 API 获取。任何帮助或指导将不胜感激。单击按钮时,我想从 API 中获取一个新的随机笑话并以纯文本形式显示在浏览器中。
const fetchDataBtn = document.querySelector("#fetch-data");
const result = document.querySelector("#result");
// gets data from API and sets the content of #result div
async function getData() {
result.innerText = "Loading....";
try {
const res = await fetch("http://api.icndb.com/jokes/random");
const jsonResult = await res.json();
result.innerText = JSON.stringify(jsonResult, null, 2);
} catch (error) {
console.log(error);
}
}
// add event listener for #fetch-data button
fetchDataBtn.addEventListener("click", getData);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ChuckNorrisJokes</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="landing">
<div class="title">
<h1>Chuck Norris Jokes</h1>
</div>
<button id="fetchdata">Get More Jokes</button>
<div id="result"></div>
</div>
<script src="script.js"></script>
</body>
</html>
解决方案
您只需要访问正确的值,而不是字符串化整个对象,笑话值已经是一个字符串:
result.innerText = jsonResult.value.joke;
推荐阅读
- javascript - 当我们使用fire base auth注册时如何添加用户名
- javascript - Javascript - 当服务器发送大响应时,WebSocket 客户端未收到 onmessage 事件
- swift - 关于 Swift 中带有 GCD 的 UDP 套接字的“表达式类型不明确”错误(DispatchQueue)
- vb.net - bc30526 属性单元格是“只读”DataGridView1 到 excel
- google-sheets - 如何将文本连接到 Google 表格中的过滤列?
- git - Git rebase:我必须先有一个干净的工作目录吗?
- python - 使用条件计算数据集属性上的值
- python - 使用子进程时如何留在虚拟环境中?
- postman - 如何使用邮递员获取here-api的访问令牌
- python - 在 python 的多服务系统中使用日志的最佳实践是什么?