Files
front-end-example/05-es6-plus/08-fetch-and-json/starter.js
2026-03-23 14:56:04 +08:00

26 lines
849 B
JavaScript

const loadButton = document.getElementById("load-btn");
const status1 = document.getElementById("status");
const output = document.getElementById("output");
// 任务:
// 1. 点击按钮后把状态改成“加载中...”
// 2. 用 fetch 请求 https://jsonplaceholder.typicode.com/posts/1
// 3. 用 await 等待响应对象
// 4. 调用 res.json() 解析数据
// 5. 把 title 和 body 渲染到页面
// 6. 失败时显示“加载失败”
loadButton.addEventListener("click", async () => {
status1.textContent = "加载中..."
try {
let a = await fetch("https://jsonplaceholder.typicode.com/posts/1")
let data = await a.json()
status1.textContent = "加载成功"
const { title, body } = data
output.textContent = `title:${title}
body:${body}`
} catch (error) {
status1.textContent = "加载失败"
}
})