My code:
<script type="text/javascript">
var x = 1;
var data = JSON.parse( document.getElementById('json').innerHTML);
var next = data['next'];
var jsonData = data['data'];
while (next != null) {
x = x+1;
var nextFileUrl = data['next'];
console.log('next:', nextFileUrl);
const xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
data = this.response;
next = JSON.parse(this.response)['next'];
console.log('newNext:',next);
newJsonData = JSON.parse(this.response)['data'];
console.log('newJsonData:',newJsonData);
jsonData['data'].push(newJsonData);
}
});
xhr.open("GET", nextFileUrl);
xhr.send(null);
}
</script>
Data example:
{
"next" : "path2",
"data" : "some data here"
}
I have multiple JSON files described as above that I need to access consecutively, in a "while next != null" kind of loop, starting with the data that's already in the page. For every call, I need to get the data value, and do something with it, and then make the next call. Currently, my code seems to constantly be logging the result from the first response only.
I'm fairly new to javascript and ajax, and have no experience with jquery. I can't use fetch, as I need the solution to work for all browsers. I'm looking for the best solution to this between JS, Ajax and JQuery if someone can point me in the right direction.