I’ve been trying to access the content of a simple JSON file I’ve set up by following the guidance here - Load JSON file locally using pure Javascript - so far without success though.
I’m not seeing any errors on load, but on calling the init()
function in the console, I’m just getting undefined
back. Both the script and the JSON files sit within the same folder on my QNAP, so the file path should be correct. What have I missed?
PS. I want to pull the JSON into an object I can then work with.
script.js
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'simcard.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
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);
}
function init() {
loadJSON(function(response) {
// Parse JSON string into object
var actual_JSON = JSON.parse(response);
});
}
simcard.json
{
"simCards": [
{
"acct": "xyz0001",
"mobNum": "503245001",
"simId": "att1234560",
"telco": "AT&T",
"activated": "2015-11-20",
"added": "2015-11-21",
"completed": false
},
{
"acct": "xyz0002",
"mobNum": "504245002",
"simId": "att1234561",
"telco": "AT&T",
"activated": "2015-12-25",
"added": "2015-12-25",
"completed": false
},
{
"acct": "xyz0003",
"mobNum": "506245003",
"simId": "att1234562",
"telco": "AT&T",
"activated": "2015-12-29",
"added": "2016-01-01",
"completed": false
},
{
"acct": "xyz0004",
"mobNum": "555245004",
"simId": "btx1234560",
"telco": "BT",
"activated": "2016-02-12",
"added": "2016-02-14",
"completed": false
},
{
"acct": "xyz0005",
"mobNum": "506245005",
"simId": "o2x4446661",
"telco": "O2",
"activated": "2016-03-18",
"added": "2016-04-20",
"completed": false
},
{
"acct": "xyz0006",
"mobNum": "505245006",
"simId": "ora3453452",
"telco": "Orange",
"activated": "2016-01-07",
"added": "2016-03-28",
"completed": false
}
]
}