select2 插件加载后端数据

//html

  

function selectRoomId(select) {
    $(select).select2({
        ajax: {
            url: webroot + "/spaceRoom/listRoom?buildingId=&floor=",
            dataType: 'json',
            delay: 250,
            data: function(params) {
                var query = {
                    code: params.term
                }
                return query;
            },
            processResults: function(data, params) {
                //请求接口返回数据
                params.page = params.page || 1;
                return {
                    results: data.result
                };
            },
            cache: true
        },
        //options
        language: "zh-CN",
        placeholder: '请输入房间号',
        allowClear: true,
        width: '300px',
        //键盘选择事件
        escapeMarkup: function(markup) {
            return markup;
        },
        minimumInputLength: 1,
        templateResult: formatRepo,
        templateSelection: formatRepoSelection
    });
}
// 数据列表
function formatRepo(repo) {
    if (repo.loading) {
        return repo.text;
    }
    var markup = "
"; markup += "
" + "
" + repo.roomPath + "
"; return markup; } //选择填入内容和返回字段 function formatRepoSelection(repo) { return repo.text || repo.roomPath || repo.id; }

//调用

var roomIds = $('#roomList');
selectRoomId(roomIds);

 

 //这里是post请求,传参为json(上面是get请求)

function selectRoomId(select) {
    $(select).select2({
        ajax: {
            url: webroot + '/spaceRoom/listRoom',
            dataType: 'json',
            delay: 250,
            type:'POST',
            contentType: "application/json",
            data: function(params) {
                var paramss = {
                    code: params.term
                };
                return JSON.stringify(paramss);
            },
            processResults: function(data, params) {
                //请求接口返回数据
                params.page = params.page || 1;
                return {
                    results: data.result
                };
            },
            cache: true
        },
        //options
        language: "zh-CN",
        placeholder: '请输入房间号',
        allowClear: true,
        width: '300px',
        //键盘选择事件
        escapeMarkup: function(markup) {
            return markup;
        },
        minimumInputLength: 1,
        templateResult: formatRepo,
        templateSelection: formatRepoSelection
    });
}
// 数据列表
function formatRepo(repo) {
    if (repo.loading) {
        return repo.text;
    }
    var markup = "
"; markup += "
" + "
" + repo.roomPath + "
"; return markup; } //选择填入内容和返回字段 function formatRepoSelection(repo) { return repo.text || repo.roomPath || repo.id; }

 

转载于:https://www.cnblogs.com/Byme/p/8435753.html

你可能感兴趣的:(select2 插件加载后端数据)