【发布时间】:2019-01-07 18:23:09
【问题描述】:
我正在尝试使用Selectize 在客户端为产品分配属性。
在Laravel 中,针对Ajax 请求,我从Controller 返回了一个JSON 对象,如下所示:
$attribs = AttributeClass::find($request->id)->attributes;
$attributes = array();
foreach($attribs as $attrib){
$options = array();
foreach($attrib->options as $opt){
$options[] = array(
'id' => $opt->id,
'name' => $opt->name
);
}
$attributes[] = array(
'id' => $attrib->id,
'name' => $attrib->name,
'options' => $options
);
}
return response()->json([
'attributes' => $attributes
]);
JSON 输出如下所示:
"{"attributes":[
{"id":15,
"name":"Color",
"options":[
{"id":63,"name":"Red"},
{"id":64,"name":"Black"},
{"id":65,"name":"White"},
]},
{"id":16,
"name":"Material",
"options":[
{"id":69,"name":"Leather"},
{"id":70,"name":"Rubber"},
{"id":71,"name":"Suede"},
]},
{"id":17,
"name":"Size",
"options":[
{"id":73,"name":"40"},
{"id":74,"name":"41"},
{"id":75,"name":"42"},
{"id":76,"name":"43"},
{"id":77,"name":"44"}
]}
]}"
在 DOM 中,我有一个 div 容器,ID 为 #attributesContainer。我在div 中创建了一个新的select 元素,并尝试在下面的ajax 响应中populate and selectize 提到select:
$('#attributesContainer').empty().append(
'<label class="col-md-3 control-label">Attributes</label>'+
'<div class="col-md-9">'+
'<select id="inputAttributes" name="inputAttributes" multiple></select>'+
'<span class="help-block">Choose product attributes</span>'+
'</div>'
);
var optGroups = [];
var options = [];
$.each(data.attributes, function(index, attribute) {
var newElement = {};
newElement['id'] = attribute.id;
newElement['name'] = attribute.name;
optGroups.push(newElement);
$.each(attribute.options, function(index, option){
var newElement = {};
newElement['id'] = option.id;
newElement['attribute'] = attribute.name;
newElement['name'] = option.name;
options.push(newElement);
});
});
$('#inputAttributes').selectize({
options: options,
optgroups: optGroups,
labelField: 'name',
valueField: 'id',
optgroupField: 'attribute',
optgroupLabelField: 'name',
optgroupValueField: 'id',
searchField: ['name'],
plugins: ['optgroup_columns', 'remove_button']
});
我在这里遗漏了什么或做错了什么?请指导。
PS:我还想限制用户从每一列中只选择一个值。 API 支持吗?有什么功能可以做到这一点吗?如何在Selectize.js 中实现这种行为?
【问题讨论】:
标签: javascript jquery ajax laravel selectize.js