Blogger Information
Blog 47
fans 0
comment 3
visits 45068
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
fetch应用——访问JSON数据
江流
Original
948 people have browsed it

Fetch API 提供了一个 JavaScript 接口,用于访问和操纵 HTTP 管道的一些具体部分,例如请求和响应。它还提供了一个全局 fetch() 方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源。
本程序的数量来源于:https://jsonplaceholder.typicode.com/posts

本程序有2个页面,titlepage.html和detail.html。
titlepage.html

  1. <div id="box"></div>
  2. <script>
  3. window.onload = linkList();
  4. // async 异步函数
  5. async function linkList() {
  6. const response = await fetch(
  7. "https://jsonplaceholder.typicode.com/posts"
  8. );
  9. const comments = await response.json();
  10. rander(comments);
  11. }
  12. function rander(data) {
  13. const box = document.querySelector("#box");
  14. const ul = document.createElement("ul");
  15. data.forEach((item) => {
  16. const li = document.createElement("li");
  17. li.innerHTML = `<a href="detail.html?id=${item.id}">${item.title}<a>`;
  18. ul.append(li);
  19. });
  20. box.append(ul);
  21. }
  22. </script>

css

  1. li {
  2. list-style-type: none;
  3. }
  4. a {
  5. text-decoration: none;
  6. color: #333;
  7. }

效果:

detail.html

  1. <div class="artical">
  2. <h3 class="title"></h3>
  3. <div class="body"></div>
  4. </div>
  5. <script>
  6. window.onload = getId();
  7. async function getId() {
  8. let url = location.search;
  9. let id = url.substr(4);
  10. console.log(id);
  11. fetch("https://jsonplaceholder.typicode.com/posts/" + id)
  12. .then((response) => response.json())
  13. .then((json) => {
  14. const title = document.querySelector(".title");
  15. title.textContent = json.title;
  16. const body = document.querySelector(".body");
  17. body.textContent = json.body;
  18. });
  19. }
  20. </script>

css

  1. .artical {
  2. width: 480px;
  3. margin: 0 auto;
  4. }
  5. .title {
  6. text-align: center;
  7. }
  8. .body {
  9. background-color: lightblue;
  10. color: seagreen;
  11. }

效果:

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post