【问题标题】:How to use Select2 with JSON via Ajax request?如何通过 Ajax 请求将 Select2 与 JSON 一起使用?
【发布时间】:2014-01-22 11:36:54
【问题描述】:

我的Select2 3.4.5 无法处理 JSON 数据。

这是我的 HTML 输入框:

<input class='form-control col-lg-5 itemSearch' type='text' placeholder='select item' />

…还有我的 JavaScript

$(".itemSearch").select2({
    placeholder: "Search for an Item",
    minimumInputLength: 2,
    ajax: {
        url: "/api/productSearch",
        dataType: 'json',
        quietMillis: 100,
        data: function (term, page) {
            return {
                option: term
            };
        },
        results: function (data, page) {
            var more = (page * 10) < data.total;
            return {
                results: data.itemName,
                more: more
            };
        }
    },
    formatResult: function (data, term) {
        return data;
    },
    formatSelection: function (data) {
        return data;
    },
    dropdownCssClass: "bigdrop",
    escapeMarkup: function (m) {
        return m;
    }
});

我使用 Laravel 4 创建了一个 API,每当我在文本框中输入任何内容时都会返回一个值。

如果我在文本框中输入“test”,结果如下:

[{"itemName":"Test item no. 1","id":5},
{"itemName":"Test item no. 2","id":6},
{"itemName":"Test item no. 3","id":7},
{"itemName":"Test item no. 4","id":8},
{"itemName":"Test item no. 5","id":9},
{"itemName":"Test item no. 6","id":10},
{"itemName":"Test item no. 7","id":11}]

我无法将结果添加到我的 Select2 下拉列表中。我认为formatSelectionformatResult 导致了这个问题,因为我不知道应该在上面放置什么参数。我不知道从哪里获取容器、对象和查询等参数以及它应该返回的值,还是我的 JSON 响应有误?

【问题讨论】:

    标签: javascript json laravel jquery-select2


    【解决方案1】:

    这里有一个例子

    $("#profiles-thread").select2({
        minimumInputLength: 2,
        tags: [],
        ajax: {
            url: URL,
            dataType: 'json',
            type: "GET",
            quietMillis: 50,
            data: function (term) {
                return {
                    term: term
                };
            },
            results: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return {
                            text: item.completeName,
                            slug: item.slug,
                            id: item.id
                        }
                    })
                };
            }
        }
    });
    

    很简单

    【讨论】:

    • 感谢$.map的建议
    • 你能解释一下“slug”参数吗?
    • item 是具有 completeName、slug 和 id 属性的对象。这只是一个例子,复制粘贴。
    • Slug 它是 item 的实际属性,你的 item,我添加了这个,你可以看到如何添加额外的参数 ;)
    • 我收到此错误 jquery.min.js:2 Uncaught TypeError: Cannot read property 'length' of null when my server return no result.
    【解决方案2】:

    对于select2 v4.0.0略有不同

    $(".itemSearch").select2({
        tags: true,
        multiple: true,
        tokenSeparators: [',', ' '],
        minimumInputLength: 2,
        minimumResultsForSearch: 10,
        ajax: {
            url: URL,
            dataType: "json",
            type: "GET",
            data: function (params) {
    
                var queryParameters = {
                    term: params.term
                }
                return queryParameters;
            },
            processResults: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return {
                            text: item.tag_value,
                            id: item.tag_id
                        }
                    })
                };
            }
        }
    });
    

    【讨论】:

    • 无法让它工作... :( 没有调用服务器。
    • 谢谢,我犯的错误是没有正确映射到idtext 键值。
    【解决方案3】:

    在版本 4.0.2 中略有不同只是在 processResultsresult 中:

        processResults: function (data) {
            return {
                results: $.map(data.items, function (item) {
                    return {
                        text: item.tag_value,
                        id: item.tag_id
                    }
                })
            };
        }
    

    您必须在result 中添加data.itemsitems 是 Json 名称:

    {
      "items": [
        {"id": 1,"name": "Tetris","full_name": "s9xie/hed"},
        {"id": 2,"name": "Tetrisf","full_name": "s9xie/hed"}
      ]
    }
    

    【讨论】:

    • 如果我从data.items 中删除items,我就不需要在响应中添加items 属性了吗? ;)
    • @bekicot 是的,如果您的 json 是一个数组,您只需指定 $.map(data, function (item)[ {"id": 1,"text": "One"}, {"id": 2,"text": "Two"} ]
    • 一直把我的头撞在墙上,这一切都清楚了。谢谢,select2 的文档严重缺乏。
    【解决方案4】:

    这里我给你我的例子,其中包含 --> Country flag, City, State, Country.

    这是我的输出。

    附上这两个cdn js或者链接。

    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script>
    

    js 脚本

    //for apend flag of country.
    
    function formatState (state) {
        console.log(state);
        if (!state.id) {
          return state.text;
        }
        var baseUrl = "admin/images/flags";
        var $state = $(
          '<span><img src="'+baseUrl+ '/' + state.contryflage.toLowerCase() + '.png"  class="img-flag" /> ' +state.text+ '</span>'
        );
        return $state;
      };
    
    
    $(function(){
        $("#itemSearch").select2({
        minimumInputLength: 2,
        templateResult: formatState, //this is for append country flag.
        ajax: {
            url: URL,
            dataType: 'json',
            type: "POST",
            data: function (term) {
                return {
                    term: term
                };
            },
            processResults: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return {
                            text: item.name+', '+item.state.name+', '+item.state.coutry.name,
                            id: item.id,
                            contryflage:item.state.coutry.sortname
                        }
                    })
                };
            }
    
        }
    });
    

    预期的 JSON 响应。

    [
       {
          "id":7570,
          "name":"Brussels",
          "state":{
             "name":"Brabant",
             "coutry":{
                "sortname":"BE",
                "name":"Belgium",
    
             }
          }
       },
       {
          "id":7575,
          "name":"Brussels",
          "state":{
             "name":"Brabant Wallon",
             "coutry":{
                "sortname":"BE",
                "name":"Belgium",
    
             }
          }
       },
       {
          "id":7578,
          "name":"Brussel",
          "state":{
             "name":"Brussel",
             "coutry":{
                "sortname":"BE",
                "name":"Belgium",
    
             }
          }
       },
    
    ]
    

    【讨论】:

    • 但我对`数据感到困惑:函数(术语){返回{术语:术语}; },`
    【解决方案5】:

    这就是我解决问题的方法,我在数据变量中获取数据,通过使用上述解决方案,我得到了错误could not load results。我不得不在 processResults 中以不同的方式解析结果。

    searchBar.select2({
                ajax: {
                    url: "/search/live/results/",
                    dataType: 'json',
                    headers : {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                    delay: 250,
                    type: 'GET',
                    data: function (params) {
                        return {
                            q: params.term, // search term
                        };
                    },
                    processResults: function (data) {
                        var arr = []
                        $.each(data, function (index, value) {
                            arr.push({
                                id: index,
                                text: value
                            })
                        })
                        return {
                            results: arr
                        };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) { return markup; },
                minimumInputLength: 1
            });
    

    【讨论】:

      【解决方案6】:

      我的 ajax 永远不会被解雇,直到我把整个东西都包裹在里面

      setTimeout(function(){ .... }, 3000);

      我在 Vue 的挂载部分使用它。它需要更多时间。

      【讨论】:

        【解决方案7】:

        这些问题可能是由不正确的映射引起的。你确定你的结果集在“数据”中吗?在我的示例中,后端代码在“items”键下返回结果,因此映射应如下所示:

        results: $.map(data.items, function (item) {
        ....
        }
        

        而不是:

         results: $.map(data, function (item) {
            ....
            }
        

        【讨论】:

          【解决方案8】:

          如果没有触发 ajax 请求,请检查 select 元素中的 select2 类。删除 select2 类将解决该问题。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-01-17
            • 1970-01-01
            • 2016-01-30
            相关资源
            最近更新 更多