首页 > 解决方案 > 如何在浏览器中显示纯文本,从 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>

标签: javascriptjsonapi

解决方案


您只需要访问正确的值,而不是字符串化整个对象,笑话值已经是一个字符串:

result.innerText = jsonResult.value.joke;

推荐阅读