select2: “text is undefined” when getting json using ajax

人走茶凉 提交于 2019-12-02 06:02:25

问题


I'm having an issue when getting json results back to select2. My json does not return a result that has a "text" field so need to format the result so that select2 accepts "Name".

This code works if the text field in the json is set to "text" but in this case, I cannot change the formatting of the json result (code outside my control).

$("#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};
        }
    }      
});

I have looked into the documentation and found some statements you can put into the results such as

text: 'Name',

but I am still getting "text is undefined".

Thanks for any help.


回答1:


note that select2 is always in {id,text} pair so you need to specify both

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



回答2:


Thanks to @neel shah for solving my problem. i had just little problem, i didnt wanted to use extra library so thats why i changed to normal jquery. so if wanna go for normal jquery or javascript.

results: function (data, page) {
 var newData = [];
    $.each(data, function (index,value) {
        newData.push({
            id: value.Id,  //id part present in data
            text: value.DisplayString  //string to be displayed
        });
    });
}

OR

results: function (data, page) {
   var newData = [];
    for ( var i = 0; i < data.length; i++ ) {
        newData.push({
            id: data[i].Id,  //id part present in data
            text: data[i].DisplayString  //string to be displayed
        });
}

All credits go to neel shah. Thanks again.



来源:https://stackoverflow.com/questions/21160225/select2-text-is-undefined-when-getting-json-using-ajax

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