加载外部json文件的简单ajax请求

时间:2015-11-03 17:01:17

标签: javascript json ajax

我正在学习ajax ....我正在尝试从json文件发出一个基本请求,该文件与我的index.html位于同一个文件夹中,但出于某种原因,它表示未定义:(我可以看到错误在变量人身上,但我无法理解它为什么未定义....

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"
            }
  ]
}  

有什么想法吗?

干杯!!!!

1 个答案:

答案 0 :(得分:4)

尝试console.log(people);并查看变量所引用的对象。 (提示:这不是你的想法!

您的变量people指的是只有一个名为“people”的属性的对象。该属性是一个数组。因此,使用该JSON结构,您的代码可以编写:

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

(或者,我可能会重新设计JSON并删除额外的间接级别:只需编码数组本身而不将其包装在不包含任何其他内容的对象中)