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

json,XHR,FetchAPI,async,await

程序员文章站 2022-03-01 18:34:57
...

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. }