Blogger Information
Blog 31
fans 0
comment 0
visits 14286
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
json,XHR,FetchAPI,async,await
木子木杉
Original
326 people have browsed it

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. }
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post