select2下拉内容获取后台数据

controller(id给select;text给另外的input框)
@RequestMapping(value = "findUnit")
public @ResponseBody
JSONArray findUnit(TPetitionReport tPetitionReport, RedirectAttributes redirectAttributes) {
Dict dict = new Dict();
dict.setType("work_space");
List<Dict> list = dictService.findList(dict);
String st = "[";//构造json
st+="{id: '" + list.get(0).getValue()
+ "',text: '" + list.get(0).getLabel()+"'}";
for(int i= 1;i<list.size();i++){
st+=",{id: '" + list.get(i).getValue()
+ "',text: '" + list.get(i).getLabel()+"'}";
}
st+="]";
JSONArray json = JSONArray.fromObject(st);
return json;
}


jsp
$("#shouli"+index).select2({
ajax: {
url: "${ctx}/xffy/tPetitionReport/findShouli",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term
};
},
results: function (data) {
return {
results: data
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
formatSelection : function formatRepo(repo) { //选中一个后返回值
$("#score1"+index).val(repo.text);
return repo.id;
},
formatResult: function formatRepoSelection(repo) { //返回所有内容到下拉框
return repo.id;
},
initSelection: function (element, callback) { // 初始化时设置默认值
var id = $(element).val()==null?"请选择":$(element).val();
var text = $("#score1"+index).val()==null?"0":$("#score1"+index).val(); //把text的值传给input
var data = { id: id, text: text};//这里是初始化的数据,你可以通过id来从服务器上获取(ajax),再装载进去
callback(data);
}
});
posted @ 2017-05-05 14:30  爱吐泡泡的小小鱼  阅读(3468)  评论(0编辑  收藏  举报