我尝试在我的选择输入中使用select2
(v.4.0.10),并通过json文件加载选项。
JSON文件类似于:
[{
"gid": "ADF1C881",
"name": "COMPANY 1"
}, {
"gid": "d06C1AEC",
"name": "COMPANY 2"
}, {
"gid": "EB72561",
"name": "COMPANY 3"
}, {
"gid": "630BCB7",
"name": "COMPANY 4"
}, {
"gid": "A18F4D0",
"name": "COMPANY 5"
}];
HTML代码:<select class="select2-single-ajax"></select>
我的JS代码是:
$(document).ready(function () {
$('.select2-single-ajax').select2({
minimumInputLength: 2,
minimumResultsForSearch: 10,
width: "100%",
ajax: {
url: URL_TO_JSON_FILE,
dataType: "json",
type: "POST",
data: function (term) {
return {
term: term.name
};
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.gid
};
})
};
}
}
});
});
我在控制台中没有收到任何错误/警告。但是,该过滤器不起作用,因为当用户插入2个或更多字符时,它将返回所有结果...
答案 0 :(得分:0)
确保您正确提取数据processResults
我使用以下功能来设置select2选项
function LoadPreValueSelect2(url, objControl, caption, param,value) {
$.ajax({
url: url,
type: "GET",
data: param,
async: false,
success: function (data) {
var option = "";
$.each(data, function (index, object) {
option += "<option value='" + object.id + "'>" + object.text + "</option>";
});
$(objControl).html(option);
objControl.select2({
placeholder: caption
});
if (value)
$(objControl).val(value).trigger("change");
}
})
};