0

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

Sergikito
  • 25
  • 7
  • 1
    Duplicate: [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) –  Jan 17 '21 at 23:02
  • "*I try to assign that to an array defined outside in order to be able to use this data later*" - you cannot do that, the XHR is asynchronous. Any outside code wouldn't know when your requests are finished. You need to place the code that wants to use all the results inside that `if` statement where you currently have the `return;`. (Alternatively, *call* other code from that location, i.e. a callback). – Bergi Jan 17 '21 at 23:03
  • Here's example code: https://pastebin.com/G62GcW6m (just fyi, JSON is a text format that is parsed into an object or array, so calling your variable `jsonData` doesn't make sense because it's no longer JSON, just data) –  Jan 17 '21 at 23:15

0 Answers0