gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:16:49 24 4
gpt4 key购买 nike

我正在学习 ajax...我正在尝试从 json 文件发出基本请求,该文件与我的 index.html 位于同一文件夹中,但由于某种原因它显示未定义:( 我可以看到错误出现在变量 people 上,但我不明白为什么它是未定义的......

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();

地址.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"
}
]
}

有什么想法吗?

干杯!!!

最佳答案

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

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

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

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

关于javascript - 简单的ajax请求加载外部json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33504973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com