0

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:

Example photo

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>
asmmahmud
  • 4,844
  • 2
  • 40
  • 47
  • Please post what you have tried thus far, and where you have encountered difficulties. – fubar Aug 08 '17 at 02:29
  • 1
    _"keeps on generating an army of the same JSON content"_, because the url that is being requested is a static JSON file (unless some server scripts are creating it dynamically) – Patrick Evans Aug 08 '17 at 02:31
  • your code is perfectly fine - perhaps not the latest techniques, but OK for a beginner – Jaromanda X Aug 08 '17 at 02:31
  • You are loading `json_example_2.json` every time. Simply change the JSON file that you want to load. This could potentially be done using an array, and using your loop to access the index of the array. – Obsidian Age Aug 08 '17 at 02:31
  • You asked this before (and clearly deleted the question) and were **given an answer** ... you need to `document.getElementById("demo").innerHTML = ''` before the for loop, because your button is inside `
    ` and you are simply adding to existing content, so the button remains
    – Jaromanda X Aug 08 '17 at 02:32
  • 1
    no, wait ... that wasn't you ... https://stackoverflow.com/questions/45557072/how-to-fix-this-json-for-loop-in-ajax - are you a friend of [Jax](https://stackoverflow.com/users/7971466/jax) ? – Jaromanda X Aug 08 '17 at 02:35
  • 1
    I'm voting to close this question as off-topic because it's exactly the same question as https://stackoverflow.com/questions/45557072/how-to-fix-this-json-for-loop-in-ajax – Jaromanda X Aug 08 '17 at 02:37

0 Answers0