从Ajax Call中正确选择2格式化结果

时间:2014-11-26 19:50:30

标签: jquery ajax jquery-select2

我正在使用Select2,这是我的脚本,我想知道如何使用select2下拉列表的预期输出正确格式化服务器端调用的结果

 var EntitySelect = function (SelectorID, Action, Param) {
    $(SelectorID).select2({
    placeholder: "Cerca",
    minimumInputLength: 1,
    ajax: {
        type: "POST",
        url: Action,
        data: function (term, page) {
            Param.sSearch = term;
            return {                     
                     sColumns : Param.sColumns,
                     sSearch : Param.sSearch, 
                     sEntity: Param.sEntity,
                     sId: Param.sId,
            }
        },
        results: function (data) {
            return {results: data};
        },
    },
});

我的服务器端响应是一个数组数组。我想映射第一个值(id)和第二个选择文本。

0: [1, "Aliquam Ultrices Consulting"]
1: [2, "Congue In Scelerisque Foundation"]
2: [3, "Arcu Vestibulum LLC"]
3: [4, "Sed Inc."]
4: [5, "Lectus Associates"]

1 个答案:

答案 0 :(得分:0)

好的,这是解决方案,使用Jquery Map函数 http://api.jquery.com/jquery.map/

var EntitySelect = function (SelectorID, Action, Param) {
    $(SelectorID).select2({
    placeholder: "Cerca",
    minimumInputLength: 1,
    ajax: {
        type: "POST",
        url: Action,
        data: function (term, page) {
            Param.sSearch = term;
            return {                     
                     sColumns : Param.sColumns,
                     sSearch : Param.sSearch, 
                     sEntity: Param.sEntity,
                     sId: Param.sId,
            }
        },
        results: function (data) {
            var selectobj = $.map(data, function (v) {
                return {"text":v[1],"id":v[0]}
            })
            console.log(selectobj)
            return { results: selectobj };
        },
    },
    dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
});