在select2 multiselect中加载值

rkj*_*rkj 7 javascript jquery jquery-select2

我用来select2代替搜索框.

在这里我用来加载像这样的国家值

$("#countries").select2({
    multiple: true,
    tags:["India", "Japan", "Australia","Singapore"],
    tokenSeparators: [","]
});
Run Code Online (Sandbox Code Playgroud)

当我按下保存按钮时,它们被正确地提交给服务器,现在这里的问题是当我想在保存到服务器后修改国家字段时,我如何将保存的值加载到国家/地区字段.

这是我从服务器检索数据的方式

$.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. 

}
Run Code Online (Sandbox Code Playgroud)

Sub*_*hor 8

请查看下一节的文档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
          }
});
Run Code Online (Sandbox Code Playgroud)

你也可以这样做:

$.getJSON('/dataprovider?data=fetchCountriesForm', function(opts){
    $("#countries").select2({
        data: opts
    });
})
Run Code Online (Sandbox Code Playgroud)

您的JSON数据必须采用以下格式:

[{id:0,text:'enhancement'},
 {id:1,text:'bug'},
 {id:2,text:'duplicate'},
 {id:3,text:'invalid'},
 {id:4,text:'wontfix'}
]
Run Code Online (Sandbox Code Playgroud)

  • 我相信从网址检索到的数据会加载到用户事件的搜索框中.与用户类型输入一样,然后检索值并选择该值.我想要的是加载从json检索到的所有值,而不需要任何用户事件.@Kishor Subedi (2认同)

rkj*_*rkj 4

我只是使用这个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");
        } 
Run Code Online (Sandbox Code Playgroud)

此技巧加载选择框中的值。

  • 我知道这已经很旧了,所以请原谅我,但这似乎不适用于二维数组?我可以加载诸如 ('dog','cat','mouse') 之类的值,但不能加载 ('1': 'Dog', '2':'Cat', '3':'Mouse')。你能做到吗? (2认同)