简体   繁体   English

Select2 并加载 JSON 数据

[英]Select2 and load JSON data

I have read a lot of questions here, but i'm not able to solve this我在这里阅读了很多问题,但我无法解决这个问题

$('.titular').select2({
            placeholder: 'Select',
            width: '100%',
            ajax: {
                url: "/ajax/ajax.php",
                data: function(params) {
                    var query = {
                        query: params.term
                      }
                      return query;
                },
                processResults: function(data) {
                    console.log(data);

                    return {
                        results: $.map(data, function (item) {
                            return {
                                id: item.id,
                                nome: item.nome
                            }
                        })
                    };

                },
            },
            escapeMarkup: function (markup) { return markup; }

        });

And my JSON:还有我的 JSON:

[{"id":12,"nome":"Joe Bill"},{"id":13,"nome":"PJ"},{"id":14,"nome":"John"},{"id":16,"nome":"Acme"},{"id":17,"nome":"Acme2"},{"id":18,"nome":"Acme3"}]

The results are not showing and developer console shows:结果未显示,开发人员控制台显示:

jQuery.Deferred exception: Cannot use 'in' operator to search for 'length' in [{"id":16,"nome":"Acme"},{"id":17,"nome":"Acme2"},{"id":18,"nome":"Acme3"}] TypeError: Cannot use 'in' operator to search for 'length' in [{"id":16,"nome":"Acme"},{"id":17,"nome":"Acme2"},{"id":18,"nome":"Acme3"}]

I've tried to use the JSON viewed in oficial documentation, unsuccesfully...我尝试使用官方文档中查看的JSON,未成功...

I appreciate any help我感谢任何帮助

The console error means that you are passing to the map an string so you need to parse your data as json before.控制台错误意味着您正在向地图传递一个字符串,因此您需要先将数据解析为 json。 I've done a little test and it is working like this:我做了一个小测试,它是这样工作的:

processResults: function (data, params) {
        data = JSON.parse('[{ "id": 12, "nome": "Joe Bill" }, { "id": 13, "nome": "PJ" }, { "id": 14, "nome": "John" }, { "id": 16, "nome": "Acme" }, { "id": 17, "nome": "Acme2" }, { "id": 18, "nome": "Acme3" }]');

        var r = $.map(data, function (item) { return { id: item.id, text: item.nome }});
        return { results: r };
}

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM