欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

javascript中的json,XHR与Fetch

程序员文章站 2022-03-13 12:40:11
...

json

json简介

  • json是通用的,轻量化的 “数据交互格式”,用于 “前后端数据通信”
  • json独立于编程语言,本质是一个格式化字符串
  • json借用了js对象字面量的语法,简洁高效,已替代了传统的xml格式
  • json不是js对象, 但它可以与js对象之间相互转换

关键API

  • JSON.stringify(js对象,回调函数[可选],格式化字符[可选]),将js对象序列化成json,例如下列代码将一个js对象序列化成json
  1. const player={
  2. account:"376220510",
  3. name:"烈火点烟",
  4. password:"6350187",
  5. sex:"男",
  6. phone:"18959261401",
  7. };
  8. jsonStr = JSON.stringify(player);
  9. console.log(jsonStr);

可以通过回调函数选择返回的json格式,也可以选择不返回某些内容,例如下列代码

  1. const player={
  2. account:"376220510",
  3. name:"烈火点烟",
  4. password:"6350187",
  5. sex:"男",
  6. phone:"18959261401",
  7. };
  8. jsonStr = JSON.stringify(player,(key, value) => {
  9. switch (key) {
  10. case "sex":
  11. return value === "男" ? "man" : "woman";
  12. case "phone":
  13. return undefined;
  14. default:
  15. return value;
  16. }
  17. });
  18. console.log(jsonStr);

上述代码执行结果中,不返回phone属性,且将sex属性值修改成man返回

XHR

传统XHR创建一个get或者post请求需要以下步骤

  • 1.创建对象: new XMLHttpRequest();
  • 2.响应类型: xhr.responseType = “json”;
  • 3.配置参数: xhr.open(“GET”, url, true);
  • 4.请求回调: xhr.onload = () => console.log(xhr.response);
  • 5.失败回调: xhr.onerror = () => console.log(“Error”);
  • 6.发起请求: xhr.send(null);
  • 以下代码实例演示XHR如果发起一个http请求
  1. const xhr = new XMLHttpRequest();
  2. xhr.responseType = "json";
  3. let url = "http://website.io/users.php";
  4. url = "http://website.io/users.php?id=100";
  5. xhr.open("GET", url, true);
  6. xhr.onload = () => {
  7. console.log(xhr.response);
  8. render(xhr.response, btn);
  9. };
  10. xhr.onerror = () => console.log("Error");
  11. xhr.send(null);

fetch

fetch请求基于 promise, 返回一个Promise对象

  • 下列代码实例演示fetch方式发起一个http的get请求
  1. let url = "http://website.io/users.php";
  2. url = "http://website.io/users.php?id=2";
  3. fetch(url)
  4. .then(response => response.json())
  5. .then(json => {
  6. console.log(json);
  7. render(json, btn);
  8. })
  9. .catch(err => console.log("Fetch Error", err));

async,await

  • async写在函数头,声明该函数为异步函数
  • await表示后面是一个异步请求,需要等待结果
  • 以下为异步函数实例
  1. async function getUser(btn) {
  2. let url = "http://website.io/users.php";
  3. url = "http://website.io/users.php?id=3";
  4. const response = await fetch(url);
  5. const result = await response.json();
  6. console.log(result);
  7. render(result, btn);
  8. }