$(`#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([]); } }); });