How can I loop through multiple JSON objects in AJAX? Is it possible to do that in javascript with a button click event?
I found the following code, but it has the problem that the button doesn't go away, and the JSON keeps on generating an army of the same JSON content and keep appending to the div:
function x() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var employees = JSON.parse(xhr.responseText);
for (var i = 0; i < employees.length; i++) {
employee = employees[i];
document.getElementById("demo").innerHTML += '<br>' + employee.name;
}
}
};
xhr.open("GET", "json_example_2.json", true);
xhr.send();
}
<div id="demo">
<button id="bg" type="button" onclick="x()">Change Content</button>
</div>