html - Fetch API - 如何将 JSON 文件解析为 HTML?
问题描述
我正在尝试使用异步 Fetch API 将 JSON 文件解析为 HTML,但我不知道如何,请帮助我一些提示。
测验.json
"quiz": {
"q1": {
"question": "Which one is correct team name in NBA?",
"options": [
"New York Bulls",
"Los Angeles Kings",
"Golden State Warriros",
"Huston Rocket"
],
"answer": "Huston Rocket"
},
"q2": {
"question": "'Namaste' is a traditional greeting in which Asian language?",
"options": [
"Hindi",
"Mandarin",
"Nepalese",
"Thai"
],
"answer": "Hindi"
},
"q3": {
"question": "The Spree river flows through which major European capital city?",
"options": [
"Berlin",
"Paris",
"Rome",
"London"
],
"answer": "Berlin"
},
"q4": {
"question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?",
"options": [
"Pablo Picasso",
"Vincent van Gogh",
"Salvador Dalí",
"Edgar Degas"
],
"answer": "Pablo Picasso"
}
}
}
想要的结果
我只使用 JSON.parse() 和 for 循环来完成结果,但这还不够。到目前为止,我试过这个:
let button = document.getElementById("get-text-btn");
let textArea = document.getElementById("my-text-area");
let loader = document.getElementById("loader");
button.addEventListener("click", function () {
getData();
});
async function getData() {
try {
let response = await fetch('quiz.json')
if (response.status !== 200) {
throw new Error("Error while reading file.");
}
let json = await response.json()
console.log(json)
class Quiz {
constructor(question, options) {
this.question = question
this.options = options
}
getInfo() {
return "<h2>" + this.question + "</h2>" + "<br>" +
'<input type="radio">' + this.options + "<br>"
}
}
// This is where I got stuck
} catch (error) {
textArea.innerHTML = 'Fetch problem: ' + error.message;
} finally {
loader.style.display = "none";
}
}
#loader {
display: inline-block;
width: 18px;
height: 18px;
display: none;
}
#loader:after {
content: " ";
display: block;
width: 18px;
height: 18px;
margin: 2px;
border-radius: 50%;
border: 2px solid #241f1f;
border-color: #241f1f transparent #241f1f transparent;
animation: lds-dual-ring 1.2s linear infinite;
}
@keyframes lds-dual-ring {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
#my-text-area {
display: block;
width: 100%;
margin-top: 16px;
}
<button id="get-text-btn">Get Data</button>
<div id="loader"></div>
<textarea id="my-text-area" rows="30"></textarea>
必须在脚本中创建一个 Quiz 类,该类将具有一个构造函数和一个允许显示数据的方法。处理从 Fetch URL 读取的字符串后,必须对其进行分段,创建 Quiz 对象,然后使用 getInfo 方法,必须对字符串中添加的每个对象执行数据显示。我希望我已经说清楚了。
解决方案
推荐阅读
- sql - SQL如何将表绑定在一起
- c# - 如何获取 ClickOnce 创建的本地应用程序数据文件夹中文件的路径
- azure - 使用 NGINX Ingress 进行 Kubernetes 角色管理
- angular - 如何在 ProductListComponentService 中修改 pageSize
- active-directory - 使用 Google G Suite 创建分发列表(邮寄列表组)
- java - 循环遍历一个字符串并在 Java 中只返回一个字符
- ubuntu - 由于缺少 liblibxcb-xtest0,无法在 ubuntu 上安装 zoom - 但无法安装?
- wordpress - 如何在 WordPress Woocommerce 中删除或添加产品网格?
- javascript - Node.js Paypal sdk:签证卡不起作用
- amazon-web-services - 在 AWS Amplify API 和 DynamoDB 中使用空字符串