select2 是一个可以自动补全的插件。
官网地址:http://ivaynberg.github.io/select2/
使用“Loading Remote Data”的例子,利用ajax从服务器端获得json数据,展现在select2上面。
发现一个问题:不能选择这些选项。
原始代码如下:
$('#searchTasksSelectId').select2({ width : 450, placeholder : '任务名称/资源名称', minimumInputLength : 1, ajax : { // instead of writing the function to execute the request we // use Select2's convenient helper url : basePath + 'web/taskConfigure/queryTasks', dataType : 'json', quietMillis : 250, data : function(term, page) { return { q : term, // search term }; }, results : function(data, page) { // parse the results into the // format expected by Select2. // since we are using custom formatting functions we do not need // to alter the remote JSON data return { results : data.items }; }, cache : true }, initSelection : function(element, callback) { }, formatResult : repoFormatResult, // omitted for brevity, see the // source of this page formatSelection : repoFormatResult, // omitted for brevity, see the // source of this page dropdownCssClass : 'bigdrop', // apply css that makes the dropdown // taller escapeMarkup : function(m) { return m; } // we do not want to escape markup since we are displaying html in // results }); function repoFormatResult(rs) { var markup = rs.taskName + '(ID:' + rs.taskId + ',owner:' + rs.ownUserId + ')'; return markup; }
后来在网上找了一下,原因是:
Select2 使用ajax从服务器取回数据之后,要进行点选,必须知道唯一的ID。也就是给selec2添加id属性。
之后的代码是:
$('#searchTasksSelectId').select2({ width : 450, placeholder : '任务名称/资源名称', minimumInputLength : 1, id : function(rs) { return rs.taskId; }, ajax : { // instead of writing the function to execute the request we // use Select2's convenient helper url : basePath + 'web/taskConfigure/queryTasks', dataType : 'json', quietMillis : 250, data : function(term, page) { return { q : term, // search term }; }, results : function(data, page) { // parse the results into the // format expected by Select2. // since we are using custom formatting functions we do not need // to alter the remote JSON data return { results : data.items }; }, cache : true }, initSelection : function(element, callback) { }, formatResult : repoFormatResult, // omitted for brevity, see the // source of this page formatSelection : repoFormatResult, // omitted for brevity, see the // source of this page dropdownCssClass : 'bigdrop', // apply css that makes the dropdown // taller escapeMarkup : function(m) { return m; } // we do not want to escape markup since we are displaying html in // results });
参考地址:
http://stackoverflow.com/questions/15639184/cant-select-item-in-list-created-by-ui-select2
https://groups.google.com/forum/#!topic/select2/jczxIqRQp_Q