Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:
Fetch API 提供了一个 JavaScript 接口,用于访问和操纵 HTTP 管道的一些具体部分,例如请求和响应。它还提供了一个全局 fetch() 方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源。
本程序的数量来源于:https://jsonplaceholder.typicode.com/posts
本程序有2个页面,titlepage.html和detail.html。
titlepage.html
<div id="box"></div>
<script>
window.onload = linkList();
// async 异步函数
async function linkList() {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts"
);
const comments = await response.json();
rander(comments);
}
function rander(data) {
const box = document.querySelector("#box");
const ul = document.createElement("ul");
data.forEach((item) => {
const li = document.createElement("li");
li.innerHTML = `<a href="detail.html?id=${item.id}">${item.title}<a>`;
ul.append(li);
});
box.append(ul);
}
</script>
css
li {
list-style-type: none;
}
a {
text-decoration: none;
color: #333;
}
效果:
detail.html
<div class="artical">
<h3 class="title"></h3>
<div class="body"></div>
</div>
<script>
window.onload = getId();
async function getId() {
let url = location.search;
let id = url.substr(4);
console.log(id);
fetch("https://jsonplaceholder.typicode.com/posts/" + id)
.then((response) => response.json())
.then((json) => {
const title = document.querySelector(".title");
title.textContent = json.title;
const body = document.querySelector(".body");
body.textContent = json.body;
});
}
</script>
css
.artical {
width: 480px;
margin: 0 auto;
}
.title {
text-align: center;
}
.body {
background-color: lightblue;
color: seagreen;
}
效果: