gpt4 book ai didi

jquery - 我如何通过 ajax 获取此 JSON 并在 select2 中显示子项

转载 作者:行者123 更新时间:2023-12-01 03:12:52 24 4
gpt4 key购买 nike

这是 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"
}
]
}
]
}

这是我目前仅将父级名称加载到 select2 字段中的 Jquery。

$(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 加载 optgroups 创建相当于选择表单的内容?以上是我失败的尝试

最佳答案

尝试

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

关于jquery - 我如何通过 ajax 获取此 JSON 并在 select2 中显示子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22926793/

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