简体   繁体   English

如何从jQuery Ajax访问JSON元素

[英]How to access JSON element from jQuery Ajax

I want to target a specific element in my JSON file: 我想定位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"
         }

     }
  ]
}

Then it gets loaded in this js file: 然后将其加载到此js文件中:

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

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

This gives me: 这给了我:

Uncaught TypeError: Cannot read property '0' of undefined 未捕获的TypeError:无法读取未定义的属性“ 0”

You have first to parse your JSON: 您必须首先解析JSON:

var tasksData = JSON.parse(task);

Then you can loop through your tasks as below: 然后,您可以如下循环浏览任务:

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

Some observations : 一些观察:

  1. It's tasksLib , not taskLib 它是tasksLib ,而不是taskLib
  2. You should use Object.keys() method: 您应该使用Object.keys()方法:

     var keys=Object.keys(task.tasksLib[0]); console.log(task.tasksLib[0][keys[0]].id) 

 var task={ "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" } } ] } var keys=Object.keys(task.tasksLib[0]); keys.forEach(function(item){ console.log(task.tasksLib[0][item].id) }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM