JavaScript AJAX Basics (retiring) Programming AJAX Processing JSON Data

How exactly does this script add the property values between the lists tags

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
    var employees = JSON.parse(xhr.responseText);
    var statusHTML = '<ul class="bulleted">';
    for (var i=0; i<employees.length; i+=1) {
        if (employees[i].inoffice === true) {

          statusHTML += '<li class="in">'; 
      } else {
          statusHTML += '<li class="out">';
      }
     statusHTML += employees[i].name;
     statusHTML += '</li>';   
    }
   statusHTML += '</ul>';
   document.getElementById('employeeList').innerHTML = statusHTML;
  }  
}; 

xhr.open('GET', 'data/employees.json');
xhr.send();

how does the code above add property values from the JSON to inbetween the lists tags?

1 Answer

Katie Wood
Katie Wood
19,041 Points

Hi there, The key line here is this one:

statusHTML += employees[i].name;

This is where it adds the "name" value from each entry of the employees object, parsed from JSON on the fourth line of code:

var employees = JSON.parse(xhr.responseText);

This line created a JavaScript object from the JSON, which we called "employees". Then, when creating the list, we take each employee's name property and put it between the tags.

statusHTML += employees[i].name;

So "i" here is the index, and this changes with every run through the loop, which means through every run, the value of name will be different and it will be added to a new list item. Am I correct?

Katie Wood
Katie Wood
19,041 Points

That's correct - the loop will increase the index until it is equal to the length of "employees", which will mean they are all printed out.

Thank you for the answer