Blogger Information
Blog 38
fans 0
comment 0
visits 22885
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
fetch,async,await 的用法
一个好人
Original
613 people have browsed it

fetch请求:

  1. function getData(ele){
  2. const url = 'https://jsonplaceholder.typicode.com/todos/20'
  3. fetch(url).then(res => res.json()).then(json => ele.insertAdjacentHTML('afterend', `<li>${json.title}</li>`)).catch(err => console.log(err))

可以获得并显示请求结果:

  1. ullam nobis libero sapiente ad optio sint

async-await请求:

  1. async function getData(ele){
  2. const url = 'https://jsonplaceholder.typicode.com/todos/'
  3. try{
  4. const response = await fetch(url)
  5. const result = await response.json()
  6. for(let i=0; i<10; i++){ele.insertAdjacentHTML('afterend', `<li>${result[i].title}</li>`)
  7. }
  8. } catch {
  9. console.error('请求失败');
  10. }
  11. }

添加for循环,请求并显示10条记录:

  1. illo est ratione doloremque quia maiores aut
  2. molestiae perspiciatis ipsa
  3. quo adipisci enim quam ut ab
  4. illo expedita consequatur quia in
  5. qui ullam ratione quibusdam voluptatem quia omnis
  6. laboriosam mollitia et enim quasi adipisci quia provident illum
  7. et porro tempora
  8. fugiat veniam minus
  9. quis ut nam facilis et officia qui
  10. delectus aut autem

总结:

跨域的概念有点陌生,按视频练了一遍,踩了好多坑;异步请求用的比较多,通过添加循环可以获得多条记录,对Ajax已经淘汰了的说法有点吃惊!感觉挺常见的。

Correcting teacher:PHPzPHPz

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