I've been working on implementing a modular view approach for retrieving data from a JSON file in my JavaScript code, but I'm facing some issues. The snippet of code where I am trying to load the JSON file is contained within a separate JS file and looks like this:
var fileConfigModule = (function () {
var jsonData = {};
function initialize() {
loadJSON(function (json) {
jsonData = json;
});
return jsonData;
}
function loadJSON(callback) {
var request = new XMLHttpRequest();
request.overrideMimeType("application/json");
request.open('GET', './data.json', true);
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == "200") {
callback(JSON.parse(request.responseText));
}
};
request.send(null);
}
return {
loadJSON: loadJSON,
init: initialize
}
})();
I want to utilize this module in my main file to asynchronously load the JSON data using a callback function. Here's how I plan to do it:
var jsonData = fileConfigModule.init();
If anyone can offer assistance on what might be going wrong here, I would greatly appreciate it. Thank you!