Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在select2 multiselect中加载值_Javascript_Jquery_Jquery Select2 - Fatal编程技术网

Javascript 在select2 multiselect中加载值

Javascript 在select2 multiselect中加载值,javascript,jquery,jquery-select2,Javascript,Jquery,Jquery Select2,我正在使用select2代替搜索框 在这里,我用它来加载类似这样的国家/地区值 $("#countries").select2({ multiple: true, tags:["India", "Japan", "Australia","Singapore"], tokenSeparators: [","] }); 当我按下保存按钮时,它们被正确地提交到服务器,现在问题是 当我想在保存到服务器后修改国家/地区字段时,如何将保存的值加载到国家/地区字段 这就是我从服务器检

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

}
请查看
加载远程数据
部分

您将发现以下示例:

$("#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'}
]
我只是使用这个链接并使用触发器函数来加载值

$.getJSON('/dataprovider?data=fetchCountriesForm', function(opts) {
        parent.parent.parent.showLoader();
        if (opts) {
            $("#countries").val(opts).trigger("change");
        } 

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

我相信从url检索到的数据会在用户事件时加载到搜索框中。与用户输入类型一样,检索值并由用户选择值。我想在这里加载从json检索到的所有值,而不需要任何用户事件@Kishor SubediThanks@Kishor寻求帮助,但我找到了更简单的方法,我只是使用触发器函数加载值。我知道这很旧,所以请原谅,但这似乎不适用于二维数组?我可以加载诸如('dog','cat','mouse')之类的值,但不能加载('1':'dog','2':'cat','3':'mouse')。你能做到吗?