Answer the question
In order to leave comments, you need to log in
How to download and process JSON file?
Tell me, there is such a json file
[{
"id": 0,
"name": "Brent Ford",
"age": 37,
"phone": "56454545",
"phrase": "dad."
}, {
"id": 1,
"name": "Arthur Lopez",
"age": 51,
"phone": "556565",
"phrase": "kekekea."
}}
It lies next to the js file in the same folder, how can I load it into js and work with it there? Here is the code, tell me where the wrong train of thought is, and how to access this data?
const loadJSON = (callback) => {
let xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'lulz.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
var mydata = JSON.parse(response);
});
}
console.log(mydata[0].name);
console.log(mydata[0].age);
console.log(mydata[1].name);
console.log(mydata[1].age);
Answer the question
In order to leave comments, you need to log in
Your variable mydata is locally defined in the callback, and you are trying to call it from the global scope.
Read:
Closures, scope
All actions with the response of the request must be done in the callback function or with the help Promise
, since XHR is performed asynchronously.
function ajax(params) {
var request = new XMLHttpRequest();
request.open(params.method, params.url, params.async || true);
request.setRequestHeader('Content-Type', params.contentType || 'application/x-www-form-urlencoded; charset=UTF-8');
request.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
if (params.success) params.success(this.responseText, this.statusText, this.status);
} else {
if (params.error) params.error(this);
}
} else {
if (params.error) params.error(this);
}
};
request.send(params.data ? JSON.stringify(params.data) : '');
request = null;
}
ajax({
url: 'lulz.json',
method: 'GET',
contentType: 'application/json; charset=UTF-8',
success: function(response, statusText, status) {
var mydata = JSON.parse(response);
console.log(mydata[0].name);
console.log(mydata[0].age);
console.log(mydata[1].name);
console.log(mydata[1].age);
},
error: function(XHR) {
console.log('Ajax Error', XHR);
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question