xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

XMLHttpRequest API All In One

XMLHttpRequest API All In One

Web API

const loadJSON = (callback) => {
  let xobj = new XMLHttpRequest();
  xobj.overrideMimeType("application/json");
  xobj.open('GET', './data.json', true);
  // Replace 'my_data' with the path to your file
  xobj.onreadystatechange = () => {
      if (xobj.readyState === 4 && xobj.status === 200) {
          // Required use of an anonymous callback
          // as .open() will NOT return a value but simply returns undefined in asynchronous mode
          callback(xobj.responseText);
      }
  };
  xobj.send(null);
}

const init = () => {
  loadJSON((response) => {
      // Parse JSON string into object
      let actual_JSON = JSON.parse(response);
      console.log('actual_JSON =', JSON.stringify(actual_JSON, null, 4));
  });
}

init();




https://cdn.xgqfrms.xyz/json/cats.json

demo



local JSON file loader in js

https://www.cnblogs.com/xgqfrms/p/12581119.html

refs

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

Ajax

https://developer.mozilla.org/en-US/docs/Glossary/AJAX



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2021-03-05 23:37  xgqfrms  阅读(65)  评论(5编辑  收藏  举报