我在學習ajax ....我試圖從json文件發出一個基本請求,它與我的index.html位於同一個文件夾中,但由於某種原因它說未定義:(我可以看到錯誤是可變的人,但我不能趕上爲什麼它未定義....簡單的ajax請求加載外部json文件
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"
}
]
}
任何想法?
乾杯!!!!
'people.length'有沒有length屬性來調用 – Ramanlfc
undefined是錯誤! –
ohmg O__O我不是想打電話給任何財產....我通過整個數組的長度試圖循環:S Oux等一下....我現在意識到....長度只是用於字符串。 ..不是嗎?那我應該用什麼? :S –