If you want to use XMLHttpRequest, you need to add the event listener being sending, and this
doesn’t refer to the HTTP request.
function openJson(file, callback) { // Since XMLHttpRequest is async, you will either need a callback function or use promises.
var httpReq = new XMLHttpRequest();
httpReq.onreadystatechange = function() { // you can still use addEventListener if you want
if (httpReq.readyState === XMLHttpRequest.DONE) { // I didn't know about that enum
if (httpReq.status == 200) { // Got 200 OK
callback( JSON.parse(httpReq.response) );
} else {
// Error
}
}
}
httpReq.open("GET", "c:/test.json");
httpReq.send();
}
Using promises
function openJSON(file) {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState === 4) {
if (req.status === 200) {
resolve( JSON.parse(req.response) );
} else {
reject(req.status);
}
}
}
req.open("GET", file);
req.send();
});
}
openJSON("c:/test.json").then(function(json) {
console.log(json);
}).catch(function(status) {
console.error(status);
});