小编典典

select2:使用ajax获取json时,“文本未定义”

ajax

将json结果返回到select2时出现问题。我的json没有返回具有“文本”字段的结果,因此需要格式化结果,以便select2接受“名称”。

如果json中的文本字段设置为“文本”,则此代码有效,但是在这种情况下,我无法更改json结果的格式(我控制范围之外的代码)。

$("#e1").select2({                                
    formatNoMatches: function(term) {return term +" does not match any items." },
    ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
    url: "localhost:1111/Items.json",
    dataType: 'jsonp',
    cache: true,
    quietMillis: 200,
    data: function (term, page) {
            return {
                q: term, // search term
                p: page,
                s: 15               
            };
        },
    results: function (data, page) { // parse the results into the format expected by Select2.          
        var numPages = Math.ceil(data.total / 15);                
        return {results: data.Data, numPages: numPages};
        }
    }      
});

我查看了文档,发现一些可以放入结果中的语句,例如

text: 'Name',

但我仍然收到“文本未定义”的信息。

谢谢你的帮助。


阅读 253

收藏
2020-07-26

共1个答案

小编典典

请注意,select2始终为{id,text}对,因此您需要同时指定两个

results: function (data, page) {
            var newData = [];
            _.each(data, function (item) {
                newData.push({
                    id: item.Id  //id part present in data 
                  , text: item.DisplayString  //string to be displayed
                });
            });
            return { results: newData };
        }
    },
2020-07-26