您的位置:首页 > 编程语言 > Go语言

select2 4.02 实现类似google搜索条的 ajax remote data功能

2015-08-17 23:17 549 查看
构建一个 select2 的 下拉框,

这里注意,不能用input 来构建了
<select id="park_code"></select>


初始化成select2 对象

    $("#park_code").select2({
        placeholder: "选择一个停车场",
        ajax: {
            url: "/park_seek/",
            dataType: 'json',
            delay: 500,
            data: function (params) {
                return {
                    q: params.term, // search term
                    page: params.page
                };
            },
            processResults: function (data, page) {
            // parse the results into the format expected by Select2.
            // since we are using custom formatting functions we do not need to
            // alter the remote JSON data
                console.debug("ajax返回的对象是:")
                console.debug(data.items)
                return {
                    results: data.items
                };
            },
            cache: true
        },
        escapeMarkup: function (markup) { 
            console.debug(markup)
            return markup; 
        }, // let our custom formatter work
        minimumInputLength: 1,  //至少输入多少个字符后才会去调用ajax
        maximumInputLength: 20, //最多能输入多少个字符后才会去调用ajax
        minimumResultsForSearch: 1,
        width: "260px",
        templateResult: formatRepo, 
        templateSelection: formatRepoSelection,
    });

    $("#park_code").on("change",function (e){
        can_analyse();
    })


/* 这里2个函数是用于查询到内容后,显示在select2的下拉框里面 */
function formatRepo (repo) {
if (repo.loading) return repo.text;
repo.text = repo.name
repo.id = repo.code
var markup = '<div class="clearfix">' +
'<div class="col-sm-4">' + repo.code + '</div>' +
'<div class="col-sm-20">' + repo.name + '</div>' +
'</div>';

return markup;
}

function formatRepoSelection (repo) {
repo.selected = true;
repo.code = repo.id
repo.name = repo.text
if(repo.code == null || repo.code == ""){
repo.text = '请选择一个停车场'
repo.name = repo.text
}
$("#park_name").val(repo.name);
console.debug(repo);
return repo.code ;
}
/* 这里2个函数是用于查询到内容后,显示在select2的下拉框里面  end */


通过其他的js函数对这个select2 进行赋值

$("#park_code").empty().append('<option id="'+code+'" value="'+code+'">'+name+'</option>').trigger('change');
注意:这里要trigger 这个 change 的 事件,这样才会调用formatRepoSelection 这个方法,并且刷新UI。

后台提供的json对象

{

items:

[

{

id: "02469",

code: "02469",

name: "大树路4"

},

{

id: "02470",

code: "02470",

name: "大树路2"

},

{

id: "02779",

code: "02779",

name: "大树路1"

},

{

id: "02679",

code: "02679",

name: "大树路3"

}

]

}

注意几个问题:

1.如果返回的json里面没有id。则会出现查询的对象无法选择的问题。处理方式,就是在返回的josn对象里面加入 id 这个唯一标示

相关内容/article/4014381.html

2.formatRepoSelection函数中,缺省的是处理repo 对象 的 id 和 text 这2个属性,而我这里定义的json是是code 和 name,所以需要把code 和 name 复制到 id 和 text里面。否则没法显示在界面上。另外一种简单的处理方法,可以把json对象直接变成 id 和 text的结构。这样就不用定制 select2 里面的方法了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: