如何通过带有子项的ajax获取此JSON以在select2中显示

时间:2014-04-08 03:05:42

标签: jquery jquery-select2

这是JSON

{
 "fields": [
  {
   "id": 2,
   "name": "philosophy",
   "children": [
    {
     "id": 2,
     "name": "ethics",
     "field_id": 2,
     "created_at": "2014-04-07T21:04:48.851Z",
     "updated_at": "2014-04-07T21:04:48.851Z"
    }
   ]
  },
  {
   "id": 1,
   "name": "sociology",
   "children": [
    {
     "id": 1,
     "name": "media",
     "field_id": 1,
     "created_at": "2014-04-07T15:45:49.013Z",
     "updated_at": "2014-04-07T15:45:49.013Z"
    },
    {
     "id": 3,
     "name": "objects",
     "field_id": 1,
     "created_at": "2014-04-08T00:47:23.758Z",
     "updated_at": "2014-04-08T00:47:23.758Z"
    }
   ]
  }
 ]
}

这是我现有的Jquery,它目前只将父级的名称加载到select2字段中。

$(document).ready(function() {
  $('#topics').select2({
    minimumInputLength: 1,
    multiple: true,
    tokenSeparators: [" "],
    ajax: {
      url: "/fields.json",
      dataType: "json",
      results: function(data, page) {
        return {
          results: $.map( data.fields, function(fields, i) {
            return { text: fields.name,  }
          } )
        }
      }
    }
  });
});

如何通过ajax加载optgroup来创建相当于选择表单的内容?以上是我失败的尝试

2 个答案:

答案 0 :(得分:4)

尝试

results: function (data, page) {
    return {
        results: $.map(data.fields, function (field, i) {
            return {
                text: field.name,
                children: $.map(field.children, function(child){
                    return {
                        id: child.id,
                        text: child.name
                    }
                })
            }
        })
    }
}

演示:Fiddle

来源:Ticket

答案 1 :(得分:0)

可选的选项,可以使用formatResult格式化元素,例如:

...
ajax: {
...
  results: function (data, page) {
    return {results: data.fields};
  }
},
formatResult: function(field) {
  return field.name;
}
...