javascript Select2 TypeError: data.results 未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20285234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:08:46  来源:igfitidea点击:

Select2 TypeError: data.results is undefined

javascriptjquery-select2

提问by test

Am trying to use Select2 to load remote data using ajax / json but i keep getting an error as:

我正在尝试使用 Select2 使用 ajax/json 加载远程数据,但我不断收到错误消息:

TypeError: data.results is undefined

类型错误:data.results 未定义

My code is :

我的代码是:

$('#tags').select2({
                ajax: {
                    url: 'http://localhost:8090/getallusers',
                    dataType: 'json',
                    quietMillis: 100,
                    data: function (term) {
                        return {
                            term: term
                        };
                    },
                    results: function (data) {
                        return data;
                        }

                    }

            });

I really Don't Understand the Problem !

我真的不明白这个问题!

回答by Irvin Dominin

Select2 needs the results as a collection of objects with id: and text: attributes.

Select2 需要将结果作为具有 id: 和 text: 属性的对象集合。

Like:

喜欢:

[{ 'id': 1, 'text': 'Demo' }, { 'id': 2, 'text': 'Demo 2'}]

[{ 'id': 1, 'text': 'Demo' }, { 'id': 2, 'text': 'Demo 2'}]

Try, to reformat you response like:

尝试重新格式化您的响应,例如:

$('#tags').select2({
    ajax: {
        url: 'http://localhost:8090/getallusers',
        dataType: 'json',
        quietMillis: 100,
        data: function (term) {
            return {
                term: term
            };
        },
        results: function (data) {
            var myResults = [];
            $.each(data, function (index, item) {
                myResults.push({
                    'id': item.id,
                    'text': item.first_name + " " + item.last_name
                });
            });
            return {
                results: myResults
            };
        }
    }
});