简体   繁体   English

使用initSelection ajax调用选择2显示undefined

[英]Select 2 displaying undefined using initSelection ajax call

I'm trying to preload an entry into Select2 using a remote ajax call and the initSelection function. 我正在尝试使用远程ajax调用和initSelection函数将一个条目预加载到Select2中。 My question seems to be similar to this question , however both answers don't work for me. 我的问题似乎与这个问题类似,但是这两个答案对我都不起作用。

The call works and returns the correct result in json format, the issue appears to be with the callback not sending the data object in the right format. 调用工作并以json格式返回正确的结果,问题似乎是回调没有以正确的格式发送数据对象。

j("#selectElement").select2({
    placeholder: "Placeholder text",
    multiple: false,
    minimumInputLength: 1,
    ajax: {
        url: "/getfiles",
        dataType: 'json',
        data: function (term, page) {
            return {
                q: term //search term
            };
        },
        results: function (data, page) {
            return data;
        }
    },
    initSelection: function(element, callback) {
        return j.getJSON("/getfiles?id=" + (element.val()), null, function(data) {
            if (j.isFunction(callback)) {
                //alert(JSON.stringify(data, null, 4));
                return callback(data);
            }
        });
    }
});

When I alert the data object it returns this data: 当我提醒数据对象时,它返回这个数据:

{
"results": [
    {
        "id": "1",
        "text": "Name of the file"
    }
],
"more": "false"

} }

The end result is the text "undefined" being loaded into the select2 input. 最终结果是文本“未定义”被加载到select2输入中。

I would greatly appreciate any assistance. 我非常感谢任何帮助。

Tim 蒂姆

The solution is to format the callback data like this 解决方案是像这样格式化回调数据

return callback(data.results[0]);

Credit goes to this question/answer: Select2 and initSelection callback 信用转到这个问题/答案: Select2和initSelection回调

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

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