我正在面临Jquery
Select2
的问题。我想设置一个Select2选项,以更改另一个Select2 Select-Box。
var categorySelect = $('#category_select');
var productSelect = $('#product_select');
categorySelect.select2();
productSelect.select2();
categorySelect.on('change',function () {
var categoryId = $(this).val();
var url = "{{url("/ajax/category/:category/products")}}";
url = url.replace(":category",categoryId);
$.get(url,function (res) {
var res = [
{id: 900, text: 'AABB'},
{id: 800, text: 'WWBB'},
]; // dummy response
productSelect.select2('data',res);
})
})
在这里,我遵循他们的文档,但不明白为什么要再次设置数据。
我以自己的方式解决了这个问题。我正在通过响应数据数组进行循环,并为产品选择框创建选项
var categorySelect = $('#category_select');
var productSelect = $('#product_select');
categorySelect.select2();
productSelect.select2();
categorySelect.on('change',function () {
var categoryId = $(this).val();
var url = "{{url("/ajax/category/:category/products")}}";
url = url.replace(":category",categoryId);
$.get(url,function (res) {
var res = [
{id: 900, text: 'AABB'},
{id: 800, text: 'WWBB'},
];
if(res.length > 0) {
productSelect.empty();
res.forEach(function (prod) {
var opt = $('<option>', {
'value' : prod.id
}).text(prod.text);
productSelect.append(opt);
});
}
})
});