I need to get the content of several JSON files that are located in similar URLs, and place the content in an array. The only difference between the URLs is the content after the last "/". I have gone through many similar solutions posted in stackoverflow, but I am not being able to understand how XMLHttpRequest exactly works.
I adapted this solution to my necessities, but I only managed to show the data of each JSON (twice) in the console. When I try to assign that to an array defined outside in order to be able to use this data later, it just doesn't fill the array.
This is one of the many attempts I did:
var data=0
var jsonData[]
var request = new XMLHttpRequest();
(function loop(i, length) {
if (i>= length) {
return;
}
var url = "https://url.com/profile=" + profiles[i];
request.open("GET", url);
request.onreadystatechange = function() {
if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
data = JSON.parse(request.responseText);
console.log(data);
jsonData[i]=(data)
loop(i + 1, length);
}
}
request.send();
})(0, profiles.length);
And also tried this way:
var data=0
var jsonData[]
for (var i = 0; i < profiles.length; i++) {
var url = "https://url.com/profile=" + profiles[i];
let request = new XMLHttpRequest();
request.open("GET", url);
request.onreadystatechange = function() {
if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
data = JSON.parse(request.responseText);
console.log(data);
}
jsonData.push(data)
console.log(data)
}
//console.log(data)
request.send();
//console.log(data)
}
Thanks in advance