gpt4 book ai didi

javascript - 如何从 jQuery Ajax 访问 JSON 元素

转载 作者:行者123 更新时间:2023-11-30 09:36:30 25 4
gpt4 key购买 nike

我想定位我的 JSON 文件中的特定元素:

{
"taskMeta": "Some meta info",
"tasksLib": [
{
"task001":
{
"id":"1",
"createDate":"01.02.17",
"dueDate":"02.03.17",
"author":"Author name",
"tag":"Things",
"description":"Here's a description of the todo",
"priority":"1",
"color":"danger",
"title":"btn-danger",
"content":"Here's the notes content"
},
"task002":
{
"id":"2",
"createDate":"02.02.17",
"dueDate":"05.03.17",
"author":"Author name",
"tag":"Other things",
"description":"Here's another description of the todo",
"priority":"0",
"color":"info",
"title":"Foo",
"content":"Here's some amazing content"
}

}
]
}

然后它被加载到这个 js 文件中:

$.ajax({
type: 'GET',
url: 'includes/tasks.json',
dataType: 'json',
success: function(task) {

$.each(task, function(i, task){
console.log(
task.taskLib[0].id
);
...

这给了我:

Uncaught TypeError: Cannot read property '0' of undefined

最佳答案

您必须首先解析您的 JSON:

var tasksData = JSON.parse(task);

然后您可以按如下方式循环执行您的任务:

$.each(tasksData.tasksLib, function(i, task){
console.log(task.id);
}

关于javascript - 如何从 jQuery Ajax 访问 JSON 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43238636/

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