【问题标题】:How can Select2 dropdown load results via AJAXSelect2 下拉列表如何通过 AJAX 加载结果
【发布时间】:2012-11-01 23:12:26
【问题描述】:

我有一个简单的 select2 框,它加载一个下拉菜单。

但是,每次打开选择菜单并显示 AJAX 调用的结果时,重新加载下拉菜单的最佳方法是什么? ajax 调用将返回

<option value=1>
<option value=2>

等等

我查看了 select2 文档上的 AJAX 示例,但对于我需要的内容来说,它看起来有点过于复杂。 TIA

【问题讨论】:

标签: javascript jquery ajax jquery-select2


【解决方案1】:

假设你有 html

   <p>
    Hidden field value set in the following format:
    <br />
    <em>'34:Donnie Darko,54:Heat,27:No Country for Old Men'
    </em></p>
<input type='hidden' id="e6" style="width: 500px;" value="34:Donnie Darko,54:Heat,27:No Country for Old Men"  />
<br /> <button id="save">Save</button>
<p>
After it's initialised, the hidden field value will change to:<br />
<em>'34,54,27'</em>
<br />
That is the value sent to the server
</p>​

​对于 select2 Ajax

function MultiAjaxAutoComplete(element, url) {
    $(element).select2({
        placeholder: "Search for a movie",
        minimumInputLength: 1,
        multiple: true,
        id: function(e) { return e.id+":"+e.title; },
        ajax: {
            url: url,
            dataType: 'json',
            data: function(term, page) {

                return {
                    q: term,
                    page_limit: 10,
                    apikey: "z4vbb4bjmgsb7dy33kvux3ea" //my own apikey
                };
            },
            results: function(data, page) {
                alert(data);
                return {
                    results: data.movies
                };
            }
        },
        formatResult: formatResult,
        formatSelection: formatSelection,
        initSelection: function(element, callback) {
            var data = [];
            $(element.val().split(",")).each(function(i) {
                var item = this.split(':');
                data.push({
                    id: item[0],
                    title: item[1]
                });
            });
            //$(element).val('');
            callback(data);
        }
    });
};

function formatResult(movie) {
    return '<div>' + movie.title + '</div>';
};

function formatSelection(data) {
    return data.title;
};



MultiAjaxAutoComplete('#e6', 'http://api.rottentomatoes.com/api/public/v1.0/movies.json');

$('#save').click(function() {
    alert($('#e6').val());
});

​尝试用这个进行多ajax调用! 参考-http://jsfiddle.net/JpvDt/112/

【讨论】:

  • 你能告诉我这里的 data.movi​​es 是什么吗? JSON 文件的外观如何?谢谢。
【解决方案2】:

试试这个:

    $(document).ready(function () {
        $('#Registration').select2({
            placeholder: 'Select a registration',
            allowClear: true,
            ajax: {
                quietMillis: 10,
                cache: false,
                dataType: 'json',
                type: 'GET',
                url: '@Url.Action("GetItems", "ItemsController")', //This asp.net mvc -> use your own URL
                data: function (registration, page) {
                    return {
                        page: page,
                        pageSize: 100,
                        registration: registration,
                        otherValue: $("#OtherValue").val() // If you have other select2 dropdowns you can get this value
                    };
                },
                results: function (data, page) {
                    var more = (page * pageSize) < data.total; // whether or not there are more results available
                    return { results: data.dataItems, more: more }; // notice we return the value of more so Select2 knows if more results can be loaded
                }
            },
            formatResult: FormatResult,
            formatSelection: FormatSelection,
            escapeMarkup: function (m) { return m; }
        });
    });

    function FormatResult(item) {
        var markup = "";
        if (item.name !== undefined) {
            markup += "<option value='" + item.id + "'>" + item.name + "</option>";
        }
        return markup;
    }

    function FormatSelection(item) {
        return item.name;
    }

【讨论】:

    【解决方案3】:

    请参阅Select2 webpage 上的加载远程数据示例。

    每次打开它都会使用ajax动态加载选择列表中的选项。

    $("#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};
                }
            }
        });
    

    【讨论】:

      【解决方案4】:

      如果您尝试默认显示带有预加载 JSON 的下拉菜单,那么当您单击归档时,您希望显示带有填充数据的下拉菜单,而无需输入单个字母,设置 minimumInputLength: 0 就像一个魅力。

      它会触发 JSON,就像您的任务是“使用 select2 加载 JSON 焦点”一样。

      我添加了代码,但由于无法在 sn-p 中使用 AJAX 远程检索 JSON,我无法使 sn-p 工作。

      请记住,这是您添加到代码中的解决方案,不要使用下面列出的解决方案。我用它来描述修复。


        $(".myContainer").select2({
          ajax: {
            url: 'myJSONpath',
            dataType: 'json',
            delay: 250,
            data: function(params) {
             return {
               q: params.term, // search term
               page: params.page
             };
            },
           minimumInputLength: 0, // so here is a trick 0 will trigger ajax call right when you click on field
           processResults: function(data, params) {
             //process your results  
           },
      

      ....然后继续使用您的其他属性...

      【讨论】:

        【解决方案5】:

        这对你有帮助

        $(document).ready(function(){
        
         $("#selUser").select2({
          ajax: { 
           url: "getData.php",
           type: "post",
           dataType: 'json',
           delay: 250,
           data: function (params) {
            return {
              searchTerm: params.term // search term
            };
           },
           processResults: function (response) {
             return {
                results: response
             };
           },
           cache: true
          }
         });
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-06-07
          • 2016-03-22
          • 2019-07-13
          • 1970-01-01
          • 2014-10-09
          • 1970-01-01
          • 2016-10-14
          相关资源
          最近更新 更多