gpt4 book ai didi

javascript - AJAX 响应从 JSON 文件返回未定义

转载 作者:行者123 更新时间:2023-11-28 07:06:02 26 4
gpt4 key购买 nike

我是 ajax 和 jquery 新手,所以要温柔。我正在做一个简单的练习,发现了一些奇怪的行为。当我尝试在控制台中显示响应时,我得到一个未定义的消息。我在这里缺少什么吗?我认为 $.ajax 方法非常简单。另外,我已确保 JSON 有效。

顺便说一句,如果有人有任何推荐资源来了解有关 JQuery 框架的 AJAX 的更多信息,请分享。

JSON:

"employees": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Anna",
"lastName": "Smith"
},
{
"firstName": "Peter",
"lastName": "Jones"
}
]

脚本:

$.ajax({
type: 'GET',
dataType: 'json',
url: 'https://api.myjson.com/bins/1f6b6',
success: function(employees){
$.each(employees, function(i, employee){
console.log(employee.firstName);
});
}
});

最佳答案

您需要使用employees.employees而不是employees

That you need iterate over the array with property name employees so you need to access it by either using employees.employees or employees['employees']

$.ajax({
type: 'GET',
dataType: 'json',
url: 'https://api.myjson.com/bins/1f6b6',
success: function(employees){
$.each(employees.employees, function(i, employee){
//----------------^-------------
console.log(employee.firstName);
});
}
});

例如检查以下代码片段

var employees = {
"employees": [{
"firstName": "John",
"lastName": "Doe"
}, {
"firstName": "Anna",
"lastName": "Smith"
}, {
"firstName": "Peter",
"lastName": "Jones"
}]
};

$.each(employees.employees, function(i, employee) {
//----------------^-------------
console.log(employee.firstName);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

关于javascript - AJAX 响应从 JSON 文件返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31708415/

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