首页 文章

Select2加载远程数据和占位符下拉列表的混合

提问于
浏览
6

我是Javascript,jQuery,Ajax和jSON世界的新手 .

我需要做的是混合使用SELECT2的2个选项

占位符

$("#e2_2").select2({
    placeholder: "Select a State"
});

加载远程数据

$("#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",
         dataType: 'jsonp',
         data: function (term, page) {
             return {
                 q: term, // search term
                 page_limit: 10,
                 apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working
             };
         },
         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 remote JSON data
             return {
                 results: data.movies
             };
         }
     },
     formatResult: movieFormatResult, // omitted for brevity, see the source of this page
     formatSelection: movieFormatSelection, // omitted for brevity, see the source of this page
     dropdownCssClass: "bigdrop" // apply css that makes the dropdown taller
 });

从Select网站可以看出,这些选项完全不同 . 当我单击“加载远程数据”字段时,它会打开一个搜索选项 . 但我不希望这样 . 我希望使用PlaceHolder示例中的可用选项下拉 .

在占位符示例中,下拉列表中可用的选项在HTML中进行了硬编码 . 我需要的是,当你打开时,它会转到jSON文件并返回json上可用的信息 .

理想情况是使用Placeholder Select2的UI以及另一个Select2示例的加载远程日期的功能(在服务器上获取json) .

任何的想法?如果2不能合并,我对任何超快的Ajax解决方案持开放态度 .

1 回答

  • 1

    如果您只需要通过ajax将数据加载到select2(不需要通过远程api进行搜索),您可以这样做:

    $.get( "/path/to/your/data.json", function(data){window.ajaxData=data;});
    $("#e2_2").select2({data: window.ajaxData, placeholder: "Select a State"});
    

    (使用全局变量通常是不好的做法,但它只是一个例子)

相关问题