$('#countryID').select2( { placeholder: "請選擇國家", ajax: { dataType: 'json', type: 'POST', delay: 500, data: ... ...
$('#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([]); } }); });