美文网首页
5分钟学会Fetch API,实现ajax请求并显示

5分钟学会Fetch API,实现ajax请求并显示

作者: 赛博剑仙_李玄器 | 来源:发表于2020-03-23 22:57 被阅读0次

本文主要介绍如何使用JS原生Feach API,获取远程数据,并利用JS方式创建HTML元素展示出来。

前置内容:

既然是获取远程数据,数据从哪来?JSONPlaceholder
JSONPlaceholder,一个免费的假数据网站,我们在开发时可以用它提供的 url 地址测试网络请求,获取一些测试使用的虚假数据和图片。

我们本次要显示的就是该网站下posts的内容。 数据来源

具体代码:

在vscode中新建两个文件,index.html和index.js其中所有的Element都放在js中。代码如下:

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script src="./index.js"></script>
  <div id="root"></div>    <!--其中id="root"的div就是放文章列表的容器-->
</body>
</html>
//写一个异步的getData函数,并在下面调用它,因为是异步的所以不会阻塞主线程,页面不会卡住。
async function getData() {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts');
  const posts = await response.json();
  console.log(posts);
  //用异步方法(await)通过fetch API获取的数据是Stream,因此需要转化成json格式。

  const root = document.querySelector("#root");
  //document.querySelector()方法,返回匹配指定选择器的第一个元素,即html里的第一个id="root"的元素。
  const ul = document.createElement("ul");
  //document.createElement(nodename)方法,通过指定名称创建一个元素,此时创建了一个ul(无序列表)元素

//遍历posts,每次遍历都创建一个li(有序列表)和a(链接)元素
  posts.forEach(post => {
    const li = document.createElement("li");
    const anchor = document.createElement("a");

    //给anchor节点添加一个Text子节点,其内容为每次遍历post个体的title
    anchor.appendChild(document.createTextNode(post.title));
    anchor.setAttribute(
      "href",
      `https://jsonplaceholder.typicode.com/posts/${post.id}`
    );
    //setAttribute(attributename,attributevalue)方法,为元素添加指定的属性,并为其赋指定的值。

    li.appendChild(anchor);
    ul.appendChild(li);
  });

  root.appendChild(ul);
}

getData();

最终结果:

显示为一个无序列表 内容列表
链接内容

教程来源:JS 原生 Fetch API ajax请求数据并展现 | HTML CSS JavaScript 前端实战

我之前学fetch通过生啃文档的方式,很痛苦。
峰华前端工程师,该up主的视频内容清晰明了,简单易懂,UI界面简洁大方,十分推荐,俺已关注。

相关文章

网友评论

      本文标题:5分钟学会Fetch API,实现ajax请求并显示

      本文链接:https://www.haomeiwen.com/subject/kkggyhtx.html