第一个.then fetch拿回来的数据,在then中执行,将对象(response)json序列化
第二个.then 将序列化后的json数据 进行控制台输出第二个.then 将序列化后的json数据 进行控制台输出第二个.then 将序列化后的json数据 进行控制台输出第二个.then 将序列化后的json数据 进行控制台输出
fetch HTML代码示范:
<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>异步请求: fetch api</title></head><body><button onclick="getUser(this)">Fetch API</button><script>function getUser() {fetch('http://ajaxtest.cn/data.php?id=3').then((response) => response.json()).then((json) => console.log(json));}</script></body></html>
ECMA2017: async,await 简化异步回调
将函数异步化: 异步函数, async
内部的fetch.then.then…拆开,按同步的方式编写
内部的异步请求,使用 await 进行描述
HTML代码示范:
<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>异步请求: fetch api</title></head><body><button onclick="getUser(this)">Fetch API</button><script>// function 前添加 async , 转为异步函数async function getUser() {let url = 'http://site.io/data.php?id=1';// 1. 等待结果再进行下一步操作,返回响应对象const response = await fetch(url);// 2. 将响应结果,转为json, json()const result = await response.json();console.log(result);}</script></body></html>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号