JS的JSON二个API、传统异步、现代异步Fetch及异步中使用 async, await的小结
1. 演示JSON的二个API
- json是通用的,数据交互格式,用于前后端数据通信。
- json独立于编程语言,本质是一个格式化字符串。
- json借用了js对象字面量的语法,简洁高效,已替代了传统的xml格式
- json不是js对象, 但它可以与js对象之间(用函数)相互转换
- json: 本质就是js对象的序列化, 即js的对象表示格式,只是转为字符串表示例如php后端生成json字符串,前端js转换为对象,实现前后端交换数据
- json字符串格式:— 所有属性必须使用双引号— 字符类型的值必须使用双引号— 不能有undefined— 最后一个值后不能有逗号
<!DOCTYPE html><html lang="en"><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>JSON的二个API</title></head><body><script>// 定义对象const user = {id: 001,name: "李小龙",nationality: "中国",gender: "male",};console.log(user);// 显示为对象// 将对象转为json字符串let jsonUser = JSON.stringify(user);console.log(jsonUser);// 显示字符串:{"id":1,"name":"李小龙","nationality":"中国"}// 第2个参数为数组时,只把相应的属性转为json字符串jsonUser = JSON.stringify(user, ["name", "nationality"]);console.log(jsonUser);// 显示结果:{"name":"李小龙","nationality":"中国"}// 第2个参数为回调函数时,传递对象索引和值jsonUser = JSON.stringify(user, (key, value) => {// 根据属性判断分支switch (key) {// 根据性别转为中文case "gender":return value === "male" ? "男" : "女";// 不输出国籍case "nationality":return undefined;case "id":return undefined;// 其他属性都输出default:return value;}});console.log(jsonUser);// 显示字符串:{"name":"李小龙","gender":"男"}// 第3个参数:格式化jsonUser = JSON.stringify(user, null, 2);console.log(jsonUser);// 显示结果为分行缩进格式显示对象属性jsonUser = JSON.stringify(user, null, "...");console.log(jsonUser);// 定义json字符串const jsonUS_TV = `{"moveTitle":"时空之轮","years":"2021","country":"美国","language":"英语","category":["动作","冒险","剧情","奇幻"]}`;// 转为js对象let classUS_TV = JSON.parse(jsonUS_TV);console.log(classUS_TV);// 显示结果为对象// 使用参数classUS_TV = JSON.parse(jsonUS_TV, (key, value) => {// 删除years属性if (key === "years") {delete this[key];} else {return value;}});console.log(classUS_TV);// 显示到页面中let html = `<h3>美剧推荐</h3><p>片名:${classUS_TV.moveTitle}</p><p>国家:${classUS_TV.country}</p><p>语言:${classUS_TV.language}</p><p>类型:${Object.values(classUS_TV.category).map((value) => `${value}`).join(",")}</p>`;const div = document.createElement("div");div.innerHTML = html;document.body.append(div);</script></body></html>
2. 异步传统方式
- 创建对象: new XMLHttpRequest();
- 响应类型: xhr.responseType = “json”;设置为返回数据类型为json
- 配置参数: xhr.open(“GET”, url, true);
- 请求回调: xhr.onload = () => console.log(xhr.response);
- 失败回调: xhr.onerror = () => console.log(“Error”);
- 发起请求: xhr.send(null);
- xhr 至少监听2个事件: load,error, 调用2个函数: open,send
- post请求,需要设置一下请求头与请求的数据,其它与get请求完全相同
<!DOCTYPE html><html lang="en"><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>异步</title></head><body><button onclick="getUserXHR(this)">查询用户信息--传统方式</button></body><script>// 请求链接,没有参数显示所有数据let url = "user.php";// 有参数显示单条数据url = "user.php?id=2";// 一、传统异步方式function getUserXHR(btn) {// 1. 创建异步对象const XHR = new XMLHttpRequest();// 2. 响应类型为jsonXHR.responseType = "json";// 3. 配置参数XHR.open("GET", url, true);// 4. 请求响应成功结果,onload方法参数为函数,不用参数// 返回结果在response对象中XHR.onload = () => {console.log(XHR.response);// 调用自定义函数显示在页面render(XHR.response, btn);};// 5. 请求失败处理XHR.onerror = () => console.log("请求错误!");// 6. 发起请求XHR.send(null);}</script><script src="function.js"></script></html>
3. 异步现代Fetch方式
语法
fetch(请求链接).then(参数=>{}) 请求成功,参数为回调函数,返回值.then(...) 链式调用.catch(...) 请求失败,参数为回调函数,错误信息
<!DOCTYPE html><html lang="en"><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异步</title></head><body><button onclick="getUser(this)">查询用户信息--Fetch方式</button></body><script>// 请求链接,没有参数显示所有数据let url = "user.php";// 有参数显示单条数据// url = "user.php?id=1";function getUser(btn) {fetch(url)// 取得返回结果,转为json对象.then((res) => res.json())// 链式调用,将json对象输出.then((js) => {console.log(js);// 调用自定义函数,在页面中显示render(js, btn);}).catch((err) => console.log("查询错误:", err));}</script><script src="function.js"></script></html>
4. 异步中使用 async, await
ECMA2017, 使用async, await, 来简化了fetch , 实现同步的方式来编写异步代码
- 在异步代码前加await,表示执行异步,要等待结果
- 函数中有await表示是异步函数,在函数前面加async表示使用 async, await可把异步按同步运行,代码从前往后一条条运行。以后常用这种方式使用异步
<!DOCTYPE html><html lang="en"><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>async, await</title></head><body><button onclick="getUser(this)">查询用户信息--Fetch方式</button></body><script>// 请求链接let url = "http://jsonplaceholder.typicode.com/users";// 函数中有await异步操作,则函数要用async表示异步函数async function getUser(btn) {// 定义常量RESPONSE,赋值为响应对象// fetch为异步运行,在前面用await表示,要等待响应结果const RESPONSE = await fetch(url);// 上面对象是json字符串,转为对象。也是异步,要等待转换结果const RESULT = await RESPONSE.json();// 调用自定义函数,在页面上显示结果render(RESULT, btn);}</script><script src="function.js"></script></html>