local JSON file loader in js
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-03-27
*
* @description
* @augments
* @example
* @link https://stackoverflow.com/a/39571547/5934465
*
*/
const log = console.log;
// import * as json from './datas.json';
// log(`json`, JSON.stringify(json), null, 4);
const loadJSON = (callback = (json = {}) => console.log(`json =
`, json)) => {
const xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', './datas.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
log(`xobj`, xobj);
// callback(xobj.responseText);
callback(xobj.response);
}
};
xobj.send(null);
}
loadJSON((response) => {
// Parse JSON string into object
const json = JSON.parse(response);
log(`json`, json);
log(`json`, JSON.stringify(json, null, 4));
});
promise
async / await version ???
refs
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!