我正在使用Select2 Ajax在我的html select上应用自动完成功能

这是select2代码:

        <script>
            $(function(){
            $(".marques-multi").select2({
                minimumInputLength: 3,
                tags: [],
                ajax: {
                    url: "user/marques",
                    dataType: 'json',
                    type: "GET",
                    quietMillis: 50,
                    data: function (term) {
                        return term;
                    },
                      processResults: function (data) {
                        return {
                          results: data
                        };
                    },
                    transport: function (params, success, failure) {
                        var $request = $.ajax(params);

                        $request.then(success);
                        $request.fail(failure);

                        return $request;
                  }
                }
            });
        });
    </script>


这是我的html:

    <select class="form-control input-sm marques-multi" name="marque"></select>


这就是URL:带有数据(www.mywebsite.com/user/marques/marques?term=nike)的“ user / marques”返回的内容:

[
{"id_marque":"50670","marque_name":"NIK HUBER GUITARS"},{"id_marque":"50671","marque_name":"NIKALAS CATLOW"},{"id_marque":"1","marque_name":"NIKE"},{"id_marque":"50672","marque_name":"NIKE"},
{"id_marque":"50673","marque_name":"NIKE"},{"id_marque":"50674","marque_name":"NIKE 6.0"},{"id_marque":"50675","marque_name":"NIKE ACCESSORIES"},{"id_marque":"50676","marque_name":"NIKE ACG"},{"id_marque":"50677","marque_name":"NIKE ACTION SPORTS"},{"id_marque":"50678","marque_name":"NIKE AIR MAX"},{"id_marque":"50679","marque_name":"NIKE BAIN"}
]


当我在select输入中以示例nik的形式编写时,我在控制台中看到请求返回此json消息,没有错误,但是select未被该数据填充,它保持空白。

最佳答案

如果可能,请将JSON上的数据属性从id_marquemarque_name更改为idtext

来自:

[
{"id_marque":"50670","marque_name":"NIK HUBER GUITARS"},{"id_marque":"50671","marque_name":"NIKALAS CATLOW"},{"id_marque":"1","marque_name":"NIKE"},{"id_marque":"50672","marque_name":"NIKE"},
{"id_marque":"50673","marque_name":"NIKE"},{"id_marque":"50674","marque_name":"NIKE 6.0"},{"id_marque":"50675","marque_name":"NIKE ACCESSORIES"},{"id_marque":"50676","marque_name":"NIKE ACG"},{"id_marque":"50677","marque_name":"NIKE ACTION SPORTS"},{"id_marque":"50678","marque_name":"NIKE AIR MAX"},{"id_marque":"50679","marque_name":"NIKE BAIN"}
]


至:

[{"id":"50670","text":"NIK HUBER GUITARS"},{"id":"50671","text":"NIKALAS CATLOW"},{"id":"1","text":"NIKE"},{"id":"50672","text":"NIKE"},
    {"id":"50673","text":"NIKE"},{"id":"50674","text":"NIKE 6.0"},{"id":"50675","text":"NIKE ACCESSORIES"},{"id":"50676","text":"NIKE ACG"},{"id":"50677","text":"NIKE ACTION SPORTS"},{"id":"50678","text":"NIKE AIR MAX"},{"id":"50679","text":"NIKE BAIN"}];


Fiddle

09-30 19:10