【问题标题】:Load values in select2 multiselect在 select2 多选中加载值
【发布时间】:2025-12-18 22:00:01
【问题描述】:

我使用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. 

}

【问题讨论】:

    标签: javascript jquery jquery-select2


    【解决方案1】:

    请在Loading Remote Data 部分下查看documentation

    你会发现像这样的例子:

    $("#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'}
    ]
    

    【讨论】:

    • 我相信从 url 检索到的数据已加载到用户事件的搜索框中。就像用户键入输入一样,然后检索值并选择该值。我在这里想要的是加载从 json 检索到的所有值,而不需要任何用户事件。 @Kishor Subedi
    • 感谢@Kishor 的帮助,但我找到了更简单的方法,我只是使用触发函数来加载值。
    【解决方案2】:

    我只是使用这个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");
            } 
    

    这个技巧在选择框中加载值。

    【讨论】:

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