在select2 multiselect中加载值
我用select2
代替搜索框。
在这里我用来加载像这样的国家值
$("#countries").select2({ multiple: true, tags:["India", "Japan", "Australia","Singapore"], tokenSeparators: [","] });
当我按下保存按钮时,它们被正确地提交给服务器,现在问题是我想在保存到服务器后修改国家/地区字段,如何将保存的值加载到国家/地区字段。
这是我从服务器检索数据的方式
$.getJSON('/dataprovider?data=fetchCountriesForm', function(opts) { //the opts here contains the json values of the countries. //what code should be written here to load the values in $('#countries).select2(); //user can add some more countries or can remove the previously added countries. }
请查看Loading Remote Data
部分下的文档 。
你会发现和例如:
$("#e6").select2({ placeholder: "Search for a movie", minimumInputLength: 1, ajax: { // instead of writing the function to execute the request we use Select2's convenient helper url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json" // Other stuffs } });
你也可以这样做:
$.getJSON('/dataprovider?data=fetchCountriesForm', function(opts){ $("#countries").select2({ data: opts }); })
您的JSON
数据必须采用以下格式:
[{id:0,text:'enhancement'}, {id:1,text:'bug'}, {id:2,text:'duplicate'}, {id:3,text:'invalid'}, {id:4,text:'wontfix'} ]
我只是使用这个http://ivaynberg.github.io/select2/#event_ext_change链接并使用触发器函数来加载值
$.getJSON('/dataprovider?data=fetchCountriesForm', function(opts) { parent.parent.parent.showLoader(); if (opts) { $("#countries").val(opts).trigger("change"); }
此技巧会在选择框中加载该值。