select2 ajax won't display json data returned

和自甴很熟 提交于 2019-12-03 16:34:56

Your data must of format [{"text":"Asante","id":12}, ...] else you need to pass {results: data, text: 'client'}

If your json string needs to use something other than "text": "something" then here's the added stuff needed: use formatResults to get the data to show up. Here's the fixed version:

$(".select").select2({
    allowClear: true,
    blurOnChange: true,
    openOnEnter: false,
    ajax: {
        url: "/surveymanagement/admin/client.cfc",
        dataType: 'json',
        data: function (term, page) {
            return {
                method: "GetClientsByName",
                name: term
            };
        },
        results: function (data, page) {
            return { results: data };
        }
    },
    formatResult: function (data) {
        return "<div class='select2-user-result'>" + data.client + "</div>";
    },
    formatSelection: function (data) {
        return data.client;
    }
});

Otherwise Arun is right that you just need to use the format [{"id":1,"text":"client"}]

Awad Haj

yes it's too old :) but i needed it today and solved it like this (using Symfony2):

$opts = [];

foreach($items as $item)

    $opts['results'][] = ['text' => $item->getXyz(), 'id' => $sk->getId()];

return new JsonResponse($opts);

the key 'results' is important

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!