选择2并加载JSON数据

时间:2018-02-22 19:44:01

标签: javascript jquery jquery-select2

我在这里已经阅读了很多问题,但我无法解决这个问题

$('.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; }

        });

我的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"}]

结果未显示,开发者控制台显示:

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"}]

我尝试使用在官方文档中查看的JSON,不成功......

我感谢任何帮助

1 个答案:

答案 0 :(得分:1)

控制台错误意味着您将字符串传递给地图,因此您需要先将数据解析为json。我做了一点测试,它的工作方式如下:

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 };
}

希望这有帮助。