博客列表 >fetch应用——访问JSON数据

fetch应用——访问JSON数据

江流
江流原创
2021年10月04日 20:37:43935浏览

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. }

效果:

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议