【问题标题】:select2: "text is undefined" when getting json using ajaxselect2:使用ajax获取json时“文本未定义”
【发布时间】:2014-02-05 06:25:55
【问题描述】:

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

如果 json 中的文本字段设置为“text”,则此代码有效,但在这种情况下,我无法更改 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',

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

感谢您的帮助。

【问题讨论】:

    标签: javascript jquery ajax json jquery-select2


    【解决方案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 };
            }
        },
    

    【讨论】:

    • 这对我有用,虽然使用了常规的 for 循环。非常感谢。
    • TypeError: _ 未定义
    • 我不得不使用 underscore.js 库。如果可以,请将其更改为正常的 for 循环,它真的会有所帮助.. 再次感谢。
    【解决方案2】:

    感谢@neel shah 解决了我的问题。我只是小问题,我不想使用额外的库,所以这就是为什么我改为普通的 jquery。 所以如果想使用普通的 jquery 或 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
            });
        });
    }
    

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

    所有的功劳都归于 neel shah。再次感谢。

    【讨论】:

      猜你喜欢
      • 2020-08-29
      • 2015-05-28
      • 1970-01-01
      • 2022-08-08
      • 2013-11-17
      • 2013-04-12
      • 2016-05-14
      • 1970-01-01
      • 2017-10-15
      相关资源
      最近更新 更多