【发布时间】:2021-12-25 04:09:18
【问题描述】:
我曾尝试使用 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>
【问题讨论】:
-
#fetch-data应该是#fetchdata -
纯文本通常应该进入
pre或code块或文本区域
标签: javascript json api