$('#countryID').select2(
{
placeholder: "请选择国家",
ajax: {
dataType: 'json',
type: 'POST',
delay: 500,
data: function (params) {
return {
SearchKey: params.term //params.term 搜索参数值
};
},
transport: async function (params, success, failure) { //这个params和上个params是不太一样,建议 console.log(params)
if (typeof (params.data.SearchKey) == "undefined") { //刚聚焦是参数值是undefined的
var data = await vm.searchCountries({}); //data是返回的绑定数据,json数组 [{"ComapnyDistrictCode":[],"ParentID":"0","Name":"阿富汗*国"},{...}]
if (data && data.length > 0) {
success(data); //插件自带的回调success函数,
} else {
failure();
}
}
else if (params.data.SearchKey.length >= 2) { //如果输入的参数值大于等于2,去搜索数据
var data = await vm.searchCountries(params.data);
if (data && data.length > 0) {
success(data);
} else {
failure();
}
}
},
processResults: function (data, page) {
var arr = [];
data.map(x => arr.push({ id: x.ID, text: x.NameEn + '(' + x.Name + ')' })); //整理绑定格式 , 放到arr里
return {
results: arr,
more: false
};
},
cache: true
},
escapeMarkup: function (markup) {
return markup;
},
// let our custom formatter work
// minimumInputLength: 2, //至少输入多少个字符后才会去调用ajax
// maximumInputLength: 20, //最多能输入多少个字符后才会去调用ajax
// minimumResultsForSearch: 1,
// width: "260px",
templateResult: function (data) {
if (data.loading) return data.text;
return "<div>" + data.text + "</div>";
},
templateSelection: function (data) {
return data.text;
}
}).on('change', function () { //onchange函数回调
// 這裡呼叫回調並傳入現在選取的 value
vm.customFrom.Country = this.value;
vm.customFrom.CountryIndex = this.selectedIndex;
this.isInitSelect = true;
});
}
},
searchCountries(params) { //异步请求数据
return new Promise(function (resolve, reject) {
$fn.post($api.getCountries, params, ret => {
if (ret.ErrorCode == 1 && ret.Data) {
resolve(ret.Data);
} else {
resolve([]);
}
});
});