eve_mf
eve_mf

Reputation: 825

simple ajax request to load external json file

I'm learning ajax.... I am trying to make a basic request from a json file, which is in the same folder as my index.html, but for some reason it says undefined :( I can see the error is on the variable people, but I can't catch why it's undefined....

html:

<div id="personName"></div>

javascript:

 var xhr = new XMLHttpRequest(); //it holds the ajax request
     xhr.onreadystatechange = function() { //callback 
             if(xhr.readyState === 4) {
               var people = JSON.parse(xhr.responseText);//it takes the string from the response and it converts it in a javascript object
               console.log(people);
                 for (var i=0; i<people.length; i += 1) {
                      var htmlCode = "<p>" + people[i].name + "</p>";
                 }                
                      document.getElementById('personName').innerHTML = htmlCode;
     } else {
         console.log(xhr.readyState);
     }
 };
 xhr.open('GET', 'addresses.json');
 xhr.send();

addresses.json:

{ 
    "people":  [    
            {
                "position"     : "1",
                "name"         : "Familia Molina Fernandez",
                "streetType"   : "C/",
                "streetName  " : "Nuria",
                "streetNumber" : "40",
                "floor"        : "",
                "flat"         : "",
                "zipCode"      : "08202",
                "city"         : "Sabadell",
                "state"        : "Barcelona",
                "country"      : "Spain"
            },
            {
                "position"     : "2",
                "name"         : "Familia Astals Fernandez",
                "streetType"   : "Avda/",
                "streetName  " : "Polinya",
                "streetNumber" : "61",
                "floor"        : "1",
                "flat"         : "1",
                "zipCode"      : "08202",
                "city"         : "Sabadell",
                "state"        : "Barcelona",
                "country"      : "Spain"
            }
  ]
}  

Any ideas?

Cheers!!!!

Upvotes: 0

Views: 546

Answers (1)

dsh
dsh

Reputation: 12214

Try console.log(people); and take a look at the object to which your variable refers. (Hint: it's not what you think it is!)

Your variable people refers to an object with only one attribute named "people". That attribute is an array. So with that JSON structure, your code could be written:

var data = JSON.parse(...)
var people = data.people;

(alternatively, I might redesign the JSON and remove the extra level of indirection: just encode the array itself without wrapping it in an object that contains nothing else)

Upvotes: 4

Related Questions