Blogger Information
Blog 18
fans 1
comment 1
visits 11229
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
js Promise与Fetch
至诚网络的博客
Original
807 people have browsed it

异步函数

  1. <script>
  2. // ajax: 异步请求 XMLHttpRequest: xhr对象 永别了, XMLHttpRequest
  3. // promise: 期约,它是一个对象, 用来表示"异步"操作的结果
  4. // 实际工作中, 并不会直接用promise,而是用fetch api进行异步请求
  5. // console.log(fetch("https://php.cn/"));
  6. // 浏览器默认是禁止通过脚本发起一个跨域请求
  7. // console.log(fetch("demo6.html"));
  8. // fetch(url).then(响应回调).then(结果处理)
  9. // console.log(1);
  10. // 这说明这个fetch是一个异步任务,加到了异步任务队列中
  11. // 将返回的"流格式"转为json
  12. // fetch("data.json")
  13. // .then((response) => response.json())
  14. // .then((json) => console.log(json));
  15. // console.log(3);
  16. // 大家做测试的时候,可以选择一些提供json测试数据的网站
  17. // fetch("https://jsonplaceholder.typicode.com/todos/5")
  18. // .then(response => response.json())
  19. // .then(data => console.log(data));
  20. // 异步函数,返回 promise
  21. // async function f1() {
  22. // return await console.log("aaaa");
  23. // }
  24. // console.log(1);
  25. // f1();
  26. // console.log(2);
  27. </script>

fetch api案例

  1. <body>
  2. <button onclick="getList()">查看留言列表</button>
  3. <div id="box">
  4. <!-- 这里显示全部的留言信息 -->
  5. </div>
  6. <script>
  7. async function getList() {
  8. // 请求500条留言
  9. const response = await fetch("https://jsonplaceholder.typicode.com/comments");
  10. const comments = await response.json();
  11. // console.log(comments);
  12. // 将所有数据渲染到页面中
  13. render(comments);
  14. }
  15. function render(data) {
  16. const box = document.querySelector("#box");
  17. // 有序列表
  18. const ol = document.createElement("ol");
  19. data.forEach(item => {
  20. console.log(item);
  21. const li = document.createElement("li");
  22. li.textContent = item.body.slice(0, 120) + "...";
  23. // textContent: 只支持纯文本
  24. // innerHTML: 支持html标签,并解析
  25. li.innerHTML = `<span style="color:green">${item.body.slice(0, 120)} ...</span><hr>`;
  26. ol.append(li);
  27. });
  28. box.append(ol);
  29. }
  30. </script>
  31. </body>
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!