Blogger Information
Blog 29
fans 0
comment 0
visits 11077
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
JavaScript 跨域请求:fetch、async
尹辉
Original
306 people have browsed it

实例演示fetch , async, await 的用法

服务器端

test1.php

  1. <?php
  2. // 允许跨域
  3. header('Access-Control-Allow-Origin: *');
  4. // 输出 JSON 字符串
  5. echo json_encode(['uname'=> '马老师', 'email'=> '5678@qq.com' ]);

1, fetch

  1. <body>
  2. <button onclick="getData()">fetch 跨域请求</button>
  3. <script>
  4. function getData() {
  5. // 1. fetch(url): 向一个url发请异步请求
  6. fetch(`http://world.io/test1.php`)
  7. // 2. then(response=>response.json()), 将返回结果转换为 JSON 字符串
  8. .then(res => res.json())
  9. // 3. then(json=>console.log(json)),接下来就可以处理第2步的 JSON 字符串了
  10. .then(json => {
  11. document.body.insertAdjacentHTML('beforeend', `<p>${json.uname}</p>`)
  12. })
  13. }
  14. </script>
  15. </body>

点击按钮,页面输出请求的数据:

2, async、await

  1. <body>
  2. <button onclick="getData(this)">async 跨域请求</button>
  3. <script>
  4. // 异步函数,前面加 async
  5. async function getData(ele) {
  6. const url = 'http://world.io/test1.php'
  7. try {
  8. // 1. 发起异步请求,等待返回结果的响应对象
  9. const response = await fetch(url)
  10. // 2. 如果响应成功,将响应结果转为json
  11. const result = await response.json()
  12. // 3. 对响应结果进行处理,例如渲染到到页面,或打印到控制台查看
  13. ele.insertAdjacentHTML('afterend', `<p>${result.email}</p>`)
  14. } catch {
  15. console.error('请求失败')
  16. }
  17. }
  18. </script>
  19. </body>

点击按钮,页面输出请求的数据:

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