1. 演示JSON的二个API

  • json是通用的,数据交互格式,用于前后端数据通信。
  • json独立于编程语言,本质是一个格式化字符串。
  • json借用了js对象字面量的语法,简洁高效,已替代了传统的xml格式
  • json不是js对象, 但它可以与js对象之间(用函数)相互转换
  • json: 本质就是js对象的序列化, 即js的对象表示格式,只是转为字符串表示
    例如php后端生成json字符串,前端js转换为对象,实现前后端交换数据
  • json字符串格式:
    — 所有属性必须使用双引号
    — 字符类型的值必须使用双引号
    — 不能有undefined
    — 最后一个值后不能有逗号
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>JSON的二个API</title>
  8. </head>
  9. <body>
  10. <script>
  11. // 定义对象
  12. const user = {
  13. id: 001,
  14. name: "李小龙",
  15. nationality: "中国",
  16. gender: "male",
  17. };
  18. console.log(user);
  19. // 显示为对象
  20. // 将对象转为json字符串
  21. let jsonUser = JSON.stringify(user);
  22. console.log(jsonUser);
  23. // 显示字符串:{"id":1,"name":"李小龙","nationality":"中国"}
  24. // 第2个参数为数组时,只把相应的属性转为json字符串
  25. jsonUser = JSON.stringify(user, ["name", "nationality"]);
  26. console.log(jsonUser);
  27. // 显示结果:{"name":"李小龙","nationality":"中国"}
  28. // 第2个参数为回调函数时,传递对象索引和值
  29. jsonUser = JSON.stringify(user, (key, value) => {
  30. // 根据属性判断分支
  31. switch (key) {
  32. // 根据性别转为中文
  33. case "gender":
  34. return value === "male" ? "男" : "女";
  35. // 不输出国籍
  36. case "nationality":
  37. return undefined;
  38. case "id":
  39. return undefined;
  40. // 其他属性都输出
  41. default:
  42. return value;
  43. }
  44. });
  45. console.log(jsonUser);
  46. // 显示字符串:{"name":"李小龙","gender":"男"}
  47. // 第3个参数:格式化
  48. jsonUser = JSON.stringify(user, null, 2);
  49. console.log(jsonUser);
  50. // 显示结果为分行缩进格式显示对象属性
  51. jsonUser = JSON.stringify(user, null, "...");
  52. console.log(jsonUser);
  53. // 定义json字符串
  54. const jsonUS_TV = `
  55. {
  56. "moveTitle":"时空之轮",
  57. "years":"2021",
  58. "country":"美国",
  59. "language":"英语",
  60. "category":["动作","冒险","剧情","奇幻"]
  61. }
  62. `;
  63. // 转为js对象
  64. let classUS_TV = JSON.parse(jsonUS_TV);
  65. console.log(classUS_TV);
  66. // 显示结果为对象
  67. // 使用参数
  68. classUS_TV = JSON.parse(jsonUS_TV, (key, value) => {
  69. // 删除years属性
  70. if (key === "years") {
  71. delete this[key];
  72. } else {
  73. return value;
  74. }
  75. });
  76. console.log(classUS_TV);
  77. // 显示到页面中
  78. let html = `
  79. <h3>美剧推荐</h3>
  80. <p>片名:${classUS_TV.moveTitle}</p>
  81. <p>国家:${classUS_TV.country}</p>
  82. <p>语言:${classUS_TV.language}</p>
  83. <p>类型:${Object.values(classUS_TV.category)
  84. .map((value) => `${value}`)
  85. .join(",")}</p>
  86. `;
  87. const div = document.createElement("div");
  88. div.innerHTML = html;
  89. document.body.append(div);
  90. </script>
  91. </body>
  92. </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请求完全相同
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>异步</title>
  8. </head>
  9. <body>
  10. <button onclick="getUserXHR(this)">查询用户信息--传统方式</button>
  11. </body>
  12. <script>
  13. // 请求链接,没有参数显示所有数据
  14. let url = "user.php";
  15. // 有参数显示单条数据
  16. url = "user.php?id=2";
  17. // 一、传统异步方式
  18. function getUserXHR(btn) {
  19. // 1. 创建异步对象
  20. const XHR = new XMLHttpRequest();
  21. // 2. 响应类型为json
  22. XHR.responseType = "json";
  23. // 3. 配置参数
  24. XHR.open("GET", url, true);
  25. // 4. 请求响应成功结果,onload方法参数为函数,不用参数
  26. // 返回结果在response对象中
  27. XHR.onload = () => {
  28. console.log(XHR.response);
  29. // 调用自定义函数显示在页面
  30. render(XHR.response, btn);
  31. };
  32. // 5. 请求失败处理
  33. XHR.onerror = () => console.log("请求错误!");
  34. // 6. 发起请求
  35. XHR.send(null);
  36. }
  37. </script>
  38. <script src="function.js"></script>
  39. </html>

3. 异步现代Fetch方式

  • 语法

    1. fetch(请求链接)
    2. .then(参数=>{}) 请求成功,参数为回调函数,返回值
    3. .then(...) 链式调用
    4. .catch(...) 请求失败,参数为回调函数,错误信息
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>Fetch异步</title>
  8. </head>
  9. <body>
  10. <button onclick="getUser(this)">查询用户信息--Fetch方式</button>
  11. </body>
  12. <script>
  13. // 请求链接,没有参数显示所有数据
  14. let url = "user.php";
  15. // 有参数显示单条数据
  16. // url = "user.php?id=1";
  17. function getUser(btn) {
  18. fetch(url)
  19. // 取得返回结果,转为json对象
  20. .then((res) => res.json())
  21. // 链式调用,将json对象输出
  22. .then((js) => {
  23. console.log(js);
  24. // 调用自定义函数,在页面中显示
  25. render(js, btn);
  26. })
  27. .catch((err) => console.log("查询错误:", err));
  28. }
  29. </script>
  30. <script src="function.js"></script>
  31. </html>

4. 异步中使用 async, await

ECMA2017, 使用async, await, 来简化了fetch , 实现同步的方式来编写异步代码

  • 在异步代码前加await,表示执行异步,要等待结果
  • 函数中有await表示是异步函数,在函数前面加async表示
    使用 async, await可把异步按同步运行,代码从前往后一条条运行。
    以后常用这种方式使用异步
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>async, await</title>
  8. </head>
  9. <body>
  10. <button onclick="getUser(this)">查询用户信息--Fetch方式</button>
  11. </body>
  12. <script>
  13. // 请求链接
  14. let url = "http://jsonplaceholder.typicode.com/users";
  15. // 函数中有await异步操作,则函数要用async表示异步函数
  16. async function getUser(btn) {
  17. // 定义常量RESPONSE,赋值为响应对象
  18. // fetch为异步运行,在前面用await表示,要等待响应结果
  19. const RESPONSE = await fetch(url);
  20. // 上面对象是json字符串,转为对象。也是异步,要等待转换结果
  21. const RESULT = await RESPONSE.json();
  22. // 调用自定义函数,在页面上显示结果
  23. render(RESULT, btn);
  24. }
  25. </script>
  26. <script src="function.js"></script>
  27. </html>

更多相关文章

  1. android camera(三):camera V4L2 FIMC
  2. android工具之TraceView学习笔记
  3. android中showSoftInput不起作用
  4. Android(安卓)NDK 开发教程三:Hello JNI 示例
  5. 《Android》Lesson21-广播+SharedPreferences
  6. android accessibility
  7. Android(安卓)yyyy-MM-dd'T'HH:mm:ss.SSS Z 格式转换 yyyy-MM-dd
  8. Android音频系统之四AudioPolicy
  9. 在SQLite数据库中获取新插入数据自增长的ID值(传智播客笔记)

随机推荐

  1. Android完全退出程序、线程
  2. Android开发错误——Android Studio中遇
  3. android 教程(2)
  4. android 拨号上网流程
  5. Android(安卓)7.0 安装包修改后无法安装
  6. android 全屏问题
  7. view的隐藏和显示
  8. 2011.10.11——— android GestureDetect
  9. Toast大全(默认,顶部,底部,各种自定义) A
  10. android 修改statusbar(二)