select2 插件加載後端數據
阿新 • • 發佈:2018-02-09
web post請求 length inpu color repo 傳參 epo oot
//html
<select class="form-group form-control" name="roomId" id="roomList" data-op="eq" data-type="L" title="請選擇租賃空間">
<option value="">全部</option>
</select>
function selectRoomId(select) { $(select).select2({ ajax: { url: webroot+ "/spaceRoom/listRoom?buildingId=&floor=", dataType: ‘json‘, delay: 250, data: function(params) { var query = { code: params.term } return query; }, processResults: function(data, params) { //請求接口返回數據 params.page = params.page || 1; return { results: data.result }; }, cache: true }, //options language: "zh-CN", placeholder: ‘請輸入房間號‘, allowClear:true, width: ‘300px‘, //鍵盤選擇事件 escapeMarkup: function(markup) { return markup; }, minimumInputLength: 1, templateResult: formatRepo, templateSelection: formatRepoSelection }); } // 數據列表 function formatRepo(repo) { if (repo.loading) { return repo.text; } var markup = "<div></div>"; markup += "<div class=‘select2-result-repository clearfix‘>" + "<div class=‘select2-result-repository__title‘>" + repo.roomPath + "</div>"; return markup; } //選擇填入內容和返回字段 function formatRepoSelection(repo) { return repo.text || repo.roomPath || repo.id; }
//調用
var roomIds = $(‘#roomList‘);
selectRoomId(roomIds);
//這裏是post請求,傳參為json(上面是get請求)
function selectRoomId(select) { $(select).select2({ ajax: { url: webroot + ‘/spaceRoom/listRoom‘, dataType: ‘json‘, delay: 250, type:‘POST‘, contentType: "application/json", data: function(params) { var paramss = { code: params.term }; return JSON.stringify(paramss); }, processResults: function(data, params) { //請求接口返回數據 params.page = params.page || 1; return { results: data.result }; }, cache: true }, //options language: "zh-CN", placeholder: ‘請輸入房間號‘, allowClear: true, width: ‘300px‘, //鍵盤選擇事件 escapeMarkup: function(markup) { return markup; }, minimumInputLength: 1, templateResult: formatRepo, templateSelection: formatRepoSelection }); } // 數據列表 function formatRepo(repo) { if (repo.loading) { return repo.text; } var markup = "<div></div>"; markup += "<div class=‘select2-result-repository clearfix‘>" + "<div class=‘select2-result-repository__title‘>" + repo.roomPath + "</div>"; return markup; } //選擇填入內容和返回字段 function formatRepoSelection(repo) { return repo.text || repo.roomPath || repo.id; }
select2 插件加載後端數據