select2的远程加载非分页实例

$("#c01-select").select2({
ajax: {
url: "data.json",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
};
},
processResults: function (data) {

var items=data.mapList; //json数组
var itemList = [];
for(var i =0; i < items.length; i++){
itemList.push({id: items[i].id, text: items[i].name});
}

/或者

*$.each(items,function(index,item){

temList.push({id: item.id, text: item.name});

})*/
return {
results: itemList
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
说明:

1.q: params.term 查询参数(params.term表示输入框中内容,q发生到服务器的参数名)

2.processResults中results: data返回数据(返回最终数据给results,如果我的数据在data.res下,
则返回data.res。这个与服务器返回json有关)

3.minimumInputLength 最小需要输入多少个字符才进行查询,与之相关的maximumSelectionLength表示
最大输入限制。

4.escapeMarkup字符转义处理

5.templateResult返回结果回调function formatRepo(repo){return repo.text},这样就可以将返回结
果的的text显示到下拉框里,当然你可以return repo.text+"1";等

6.templateSelection选中项回调function formatRepoSelection(repo){return repo.text}

7.关于返回的 json的格式:select2默认json格式为[{id:1,text:'text'},{id:2,text:'text'}],新版
严格要求这样的格式,当然你可以添加列,如:[{id:1,text:'text',name:'liu'}]

五.获取选中项

var res=$("#c01-select").select2("data")[0] ; //单选
var reslist=$("#c01-select").select2("data"); //多选
if(res==undefined)
{
alert("你没有选中任何项");
}
if(reslist.length)
{
alert("你选中任何项");
}

原文地址:https://www.cnblogs.com/keyi/p/6971918.html