Select2-Ajax獲取數據

文章最初發表於szhshp的第三邊境研究所
轉載請註明javascript

遇到一個需求: 在前端使用Select2設計一個聯想輸入dropdown, 經過Ajax動態抓取數據html

若是用純H5來實現極其簡單, 這裏須要用Select2插件來實現前端

能夠也使用H5原生onChange來進行動態提交可是這太愚蠢了, 現成的Select有更好的API啊java

花了倆小時完成了這個功能, 官方Doc說的非常模糊..git

代碼細節:github

$('select').select2({ ajax: { url: "https://api.github.com/search/repositories", dataType: 'json', data: function (params) { var query = { //請求的參數, 關鍵字和搜索條件之類的 search: params.term //select搜索框裏面的value } // Query paramters will be ?search=[term]&page=[page] return query; }, delay: 1500, processResults: function (data, params) { //返回的選項必須處理成如下格式 //var results = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }]; return { results: results //必須賦值給results而且必須返回一個obj }; } } });

參考文獻

http://select2.github.io/options.htmlajax

http://select2.github.io/examples.html#data-arrayjson

相關文章
相關標籤/搜索