博客列表 >json,XHR,FetchAPI,async,await

json,XHR,FetchAPI,async,await

木子木杉
木子木杉原创
2022年01月11日 18:23:43324浏览

json

js->json JSON.stringify

  1. const user = {
  2. name: "李同学",
  3. qq: "123456789@qq.cn",
  4. gender: "female",
  5. salary: 2000,
  6. toJSON() {
  7. return `name=${this.name},qq=${this.qq}`;
  8. },
  9. };
  10. jsonStr = JSON.stringify(user, (key, value) => {
  11. switch (key) {
  12. case "gender":
  13. return value === "female" ? "女" : "男";
  14. case "salary":
  15. return undefined;
  16. default:
  17. return value;
  18. }
  19. });

json->js JSON.parse

  1. const siteInfo = `
  2. {
  3. "name":"PHP中文网",
  4. "domain":"https://www.php.cn",
  5. "email":"123456789@qq.com",
  6. "isRecord":true,
  7. "address":"山东",
  8. "category":["视频","文章","资源"],
  9. "lesson":{
  10. "name":"json",
  11. "price":4800,
  12. "content":["js","PHP"]
  13. }
  14. }
  15. `;
  16. site = JSON.parse(siteInfo);

传统XHR

  1. function getUser1(btn) {
  2. const xhr = new XMLHttpRequest();
  3. xhr.responseType = "json";
  4. let url = "http://website.io/users.php";
  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);
  12. }

fetch

  1. fetch("https://jsonplaceholder.typicode.com/todos/1")
  2. .then(response => response.json())
  3. .then(json => console.log(json));

async,await

  1. async function getUser(btn) {
  2. let url = "https://jsonplaceholder.typicode.com/todos/1";
  3. const response = await fetch(url);
  4. const result = await response.json();
  5. console.log(result);
  6. let html = `
  7. <li>用户:${result.userId}</li>
  8. <li>id:${result.id}</li>
  9. <li>文章:${result.title}</li>
  10. <li>completed:${result.completed ? "ture" : "false"}</li>
  11. `;
  12. const ul = document.createElement("ul");
  13. ul.innerHTML = html;
  14. document.body.append(ul);
  15. }
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议