当我将值预加载到 Select2 下拉列表中时,并展开控件以输入一个值。它过滤预加载的值。当我在文本框中输入内容时,如何配置 Select2 以进行 ajax 调用(新搜索)?如果我不将值预加载到 Select2 中,则 ajax 调用工作。那我怎么能两者兼得?
我用这样的东西预加载了我的 select2 控件:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: url,
data: json,
dataType: "json",
success: function (data, textStatus) {
var json = JSON.parse(data.d);
var arrData = [];
if (json !== null && json !== undefined) {
if (json.length > 0) {
$.each(json, function (index, element) {
var item = { id: element.CommonName, text: element.CommonName, name: element.CommonName };
arrData.push(item);
});
}
}
$("[ID$=ddlDropDown]").select2({
data: arrData
});
}
});
我用这个实例化我的 Select2 控件:
$("[ID$=ddlDropDown]").select2({
ajax: {
url: url,
type: "POST",
dataType: 'json',
async: true,
contentType: "application/json; charset=utf-8",
delay: 500,
data: function (params) {
var query = {
searchString: (params.term || ""),
page: params.page
}
// Query paramters will be ?search=[term]&page=[page]
return JSON.stringify(query);
},
processResults: function (data, page) {
var json = JSON.parse(data.d);
if (json != null) {
if (json.length > 0) {
return {
results: $.map(json, function (item) {
return {
text: item.CommonName,
name: item.CommonName,
id: item.CommonName
}
})
};
} else {
return false;
}
}
else {
return false;
}
},
success: function (data, page) {
$("[ID$=ddlDropDown]").select2("data", data, true);
}
},
minimumInputLength: 2,
placeholder: "Select a Value",
disabled: false,
cache: true
});