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":"",
  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. }

更多相关文章

  1. 开发技术前线 第七期 周报
  2. Android(安卓)Bluetooth研究
  3. MySQL5.7不停业务将传统复制变更为GTID复制的实例
  4. Retrofit系列文章翻译7—在请求体里发送对象
  5. 文章关键字 ‘nodpi’
  6. [Android]发布Sqlite数据库
  7. Android异步处理系列文章
  8. Android中dalvik和传统java虚拟机的区别
  9. 一篇文章掌握MySQL的索引查询优化技巧

随机推荐

  1. php中的绘图技术详解
  2. PHP如何实现支付宝支付功能(图文详解)
  3. PHP 数组常用函数总结
  4. PHP重置数组为连续数字索引的三种方式
  5. PHP中箭头函数的实例详解
  6. PHP根据键值合并数组
  7. php单例模式 使用场景和使用方法
  8. 学习PHP死循环写法和作用
  9. PHP 简单实现延时操作
  10. 详细解读PHP中return用法(附代码)