How to use Select2 with JSON via Ajax request?

后端 未结 8 1889
遥遥无期
遥遥无期 2020-11-29 15:58

My Select2 3.4.5 is not working with JSON data.

Here is my input box on HTML:



        
8条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 16:38

    This is how I fixed my issue, I am getting data in data variable and by using above solutions I was getting error could not load results. I had to parse the results differently in 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
            });
    

提交回复
热议问题