JSON 基础知识

  • json 是通用的,轻量化的 “数据交互格式”,用于 “前后端数据通信”
  • json 独立于编程语言,本质是一个格式化字符串
  • json 借用了 js 对象字面量的语法,简洁高效,已替代了传统的 xml 格式
  • json 不是 js 对象, 但它可以与 js 对象之间相互转换
  • json 数据类型: 不支持 undefined ,没意义的数据类型
  • json: 本质就是 js 对象的序列化, 字符串表示
  • js 对象[前端] -> json 字符串[后端], js 对象的序列化

JSON.stringify: obj -> json, JS 对象转为 json 字符串

  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基础知识</title>
  8. </head>
  9. <body></body>
  10. <script>
  11. // JS对象
  12. const staff = {
  13. id: 1,
  14. name: "DASHU",
  15. email: "help_10086@foxmail.com",
  16. isMarried: "0",
  17. gender: "0",
  18. bophan: "HR-Dept",
  19. congviec: "HR",
  20. salary: 20000000,
  21. /* toJSON() {
  22. // 只返回 name,email
  23. return `name:${this.name}, email=${this.email}`;
  24. }, */
  25. };
  26. // console.log(staff);
  27. // console.log(typeof staff);
  28. // 1、序列化json: JSON.stringify
  29. let jsonStr = JSON.stringify(staff);
  30. // 第二个参数: array, callback
  31. // array
  32. jsonStr = JSON.stringify(staff, ["name", "email"]);
  33. // callback,做一些操作
  34. jsonStr = JSON.stringify(staff, (key, value) => {
  35. switch (key) {
  36. case "gender":
  37. return value === "0" ? "男" : "女";
  38. case "salary":
  39. return undefined;
  40. default:
  41. return value;
  42. }
  43. });
  44. // 第三个参数: 格式化
  45. jsonStr = JSON.stringify(staff, null, 2);
  46. jsonStr = JSON.stringify(staff, null, "**");
  47. console.log(jsonStr);
  48. // console.log(typeof jsonStr);
  49. // JSON字符串
  50. // verify: https://www.bejson.com/
  51. // 1. 所有属性必须使用双引号
  52. // 2. 字符类型的值必须使用双引号
  53. // 3. 不能有undefined
  54. // 4. 最后一个值后不能有逗号
  55. const siteInfo = `
  56. {
  57. "name":"",
  58. "domain":"https://www.php.cn",
  59. "isRecord":true,
  60. "email":"498668472@qq.com",
  61. "address":"合肥市政务新区蔚蓝商务港",
  62. "category":["视频","文章","资源"],
  63. "lesson": {
  64. "name": "第18期Web全栈线上培训班",
  65. "price": 4800,
  66. "content": ["JavaScript", "PHP", "ThinkPHP"]
  67. }
  68. }
  69. `;
  70. </script>
  71. </html>

JSON.parse: json->obj, json 字符串转为 JS 对象

  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基础知识</title>
  8. </head>
  9. <body></body>
  10. <script>
  11. // JSON字符串
  12. // verify: https://www.bejson.com/
  13. // 1. 所有属性必须使用双引号
  14. // 2. 字符类型的值必须使用双引号
  15. // 3. 不能有undefined
  16. // 4. 最后一个值后不能有逗号
  17. const siteInfo = `
  18. {
  19. "name":"",
  20. "domain":"https://www.php.cn",
  21. "isRecord":true,
  22. "email":"498668472@qq.com",
  23. "address":"合肥市政务新区蔚蓝商务港",
  24. "category":["视频","文章","资源"],
  25. "lesson": {
  26. "name": "第18期Web全栈线上培训班",
  27. "price": 4800,
  28. "content": ["JavaScript", "PHP", "ThinkPHP"]
  29. }
  30. }
  31. `;
  32. // 2、jsonStr -> jsObj: json字符串[后端] -> js对象[前端]
  33. // JSON.parse
  34. // 以前用eval
  35. let site = eval("(" + siteInfo + ")");
  36. console.log(site, typeof site);
  37. site = JSON.parse(siteInfo);
  38. site = JSON.parse(siteInfo, function (key, value) {
  39. // console.log(key, "=>", value);
  40. if (key === "email" || key === "address") {
  41. delete this[key];
  42. } else {
  43. return value;
  44. }
  45. });
  46. console.log(site);
  47. // js obj 渲染到页面中
  48. let html = `
  49. <li>网站名称: ${site.name}</li>
  50. <li>网站域名: ${site.domain.slice(8)}</li>
  51. <li>是否备案: ${site.isRecord ? "已备案" : "未备案"}</li>
  52. <li>服务内容:
  53. <ul>
  54. <li style="color:red">1. arry.map()</li>
  55. ${site.category.map((cate) => `<li>${cate}</li>`).join("")}
  56. <li style="color:red">2. arry.reduce()</li>
  57. ${site.category.reduce((acc, cur) => `${acc}</li><li>${cur}`, "")}
  58. </ul>
  59. </li>
  60. <li>课程信息:
  61. <ul>
  62. <li style="color:red"> 1: 根据键名获取值</li>
  63. ${Object.keys(site.lesson)
  64. .map((key) => `<li>${site.lesson[key]}</li>`)
  65. .join("")}
  66. <li style="color: red"> 2: 直接获取值</li>
  67. ${Object.values(site.lesson)
  68. .map((less) => `<li>${less}</li>`)
  69. .join("")}
  70. </ul>
  71. </li>
  72. `;
  73. const ul = document.createElement("ul");
  74. ul.innerHTML = html;
  75. document.body.append(ul);
  76. </script>
  77. </html>

[http://help10086.cn/0110/demo1.html]

传统 XHR 实例演示

    1. 创建对象: new XMLHttpRequest();
    1. 响应类型: xhr.responseType = “json”;
    1. 配置参数: xhr.open(“GET”, url, true);
    1. 请求回调: xhr.onload = () => console.log(xhr.response);
    1. 失败回调: xhr.onerror = () => console.log(“Error”);
    1. 发起请求: xhr.send(null);-
  • xhr 至少监听 2 个事件: load,error, 调用 2 个函数: open,send
  • post 请求,需要设置一下请求头与请求的数据,其它与 get 请求完全相同
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  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. <script src="funcShow.js"></script>
  8. <title>ajax-xhr</title>
  9. </head>
  10. <body style="display: grid; gap: 1em">
  11. <button style="width:166px;" onclick="getStaff1(this)">
  12. 获取员工信息 - XHR
  13. </button>
  14. <script>
  15. // 1. 传统 XHR,是一个对象
  16. /**
  17. * 1. 创建对象: new XMLHttpRequest();
  18. * 2. 响应类型: xhr.responseType = "json";
  19. * 3. 配置参数: xhr.open("GET", url, true);
  20. * 4. 请求回调: xhr.onload = () => console.log(xhr.response);
  21. * 5. 失败回调: xhr.onerror = () => console.log("Error");
  22. * 6. 发起请求: xhr.send(null);
  23. *
  24. * xhr 至少监听2个事件: load,error, 调用2个函数: open,send
  25. * post请求,需要设置一下请求头与请求的数据,其它与get请求完全相同
  26. */
  27. function getStaff1(btn) {
  28. // 1. 创建对象:
  29. const xhr = new XMLHttpRequest();
  30. // 2. 响应类型:
  31. xhr.responseType = "json";
  32. // 3. 配置参数:
  33. let url = "http://help10086.cn/0110/staffs.php";
  34. // url = "http://help10086.cn/0110/staffs.php?msnv=900101";
  35. xhr.open("GET", url, true);
  36. // 4. 请求回调:
  37. xhr.onload = () => {
  38. console.log(xhr.response);
  39. // 渲染到页面中
  40. render(xhr.response, btn);
  41. };
  42. // 5. 失败回调:
  43. xhr.onerror = () => console.log("Error");
  44. // 6. 发起请求:
  45. xhr.send(null);
  46. }
  47. </script>
  48. </body>
  49. </html>

[http://help10086.cn/0110/demo2.html]

Fetch API 与 async, await 实例演示

  • 语法:
    fetch(…)
    .then(…)
    .then(…)
    .catch(…)
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  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. <script src="funcShow.js"></script>
  8. <title>Fetch API</title>
  9. </head>
  10. <body>
  11. <button onclick="getStaff(this)">获取用户信息 - Fetch</button>
  12. <script>
  13. // 实际开发中, 通常不会直接去用Promise,用fetch
  14. // axios : 基于 xhr
  15. // fetch : 基于 promise, 返回一个Promise对象
  16. // console.log(fetch());
  17. /* fetch("https://jsonplaceholder.typicode.com/users")
  18. .then(response => response.json())
  19. .then(json => console.log(json)); */
  20. fetch("http://help10086.cn/0110/staffs.php")
  21. .then((response) => response.json())
  22. .then((json) => console.log(json));
  23. // 同域: 协议相同, 域名相同,端口相同,否则就是跨域请求
  24. // ECMA2017, async, await, 来简化了fetch , 实现同步的方式来编写异步代码
  25. // 异步函数,内部有异步操作
  26. async function getStaff(btn) {
  27. let url = "http://help10086.cn/0110/staffs.php";
  28. // url = "http://help10086.cn/0110/staffs.php?msnv=900101";
  29. //await: 表示后面是一个异步请求,需要等待结果
  30. const response = await fetch(url);
  31. // response响应对象,json():将返回的数据转为json
  32. const result = await response.json();
  33. console.log(result);
  34. // 渲染到页面中
  35. render(result, btn);
  36. }
  37. </script>
  38. </body>
  39. </html>

[http://help10086.cn/0110/demo6.html]

更多相关文章

  1. Android的线程使用来更新UI----Thread、Handler、Looper、TimerT
  2. android时序图 以及UML中时序图、流程图、状态图、协作图之间的
  3. android开源框架源码分析:Okhttp
  4. Android(安卓)基础UI编程1
  5. Android(安卓)颜色渲染(十) ComposeShader组合渲染
  6. Android(安卓)Handler 机制
  7. OBJECTPROPERTY与sp_rename更改对象名称的介绍
  8. 此数据库没有有效所有者,因此无法安装数据库关系图支持对象
  9. WebKit android介绍

随机推荐

  1. android去除标题栏及状态栏
  2. as引入第三方包版本不一致 Android(安卓)
  3. init.rc
  4. Android已经完全不受Google控制了
  5. Android之gif动画实现
  6. Android 调用手机系统照相机拍照
  7. Android(安卓)实现环形进度按钮circular-
  8. Android Zygote Fork
  9. 【引用】Android(安卓)CTS 测试常见问题
  10. GitHub 优秀的 Android(安卓)开源项目