使用select2实现查询结果分页显示

js代码:

$("#tag").select2({
        language : 'zh-CN',//转为中文版
        minimumInputLength: 1,//最少输入1个字符,否则不会自动查询
        //escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
        placeholder: "标签",//默认显示文案:标签
        ajax: {
            url: "/ajax_search_tag",
            dataType: 'json',
            cache: true,
            delay: 250,
            data:function (params) {
                var have_chose="";
                $.each($("#tag").find("option:selected"),function(key,val){
                    have_chose+=$(this).val()+",";
                });
                return {
                    title: params.term, // search term
                    have_chose_ids: have_chose, //已经选择的不在查询
                    page: params.page //第几页返回查询
                };
            },
            processResults: function (data,params) {//结果处理
                params.page = params.page || 1;
                return {
                    //results: (new Function("return " + data.items))(),
                    results: data.items,
                    pagination: {
                        more: (params.page * 30) < data.total_count //每页30条数据
                    }
                }
            }
        }
    });

PHP代码:

public function ajax_search_tag(){
        $title=$_GET['title'];
        $page=$_GET['page'];
        $have_chose_ids=$_GET['have_chose_ids'];
        $tag_select=$this->search_tag_page($title,$have_chose_ids,$page);
        $result=array(
            'total_count'=>$tag_select['total'],
            'incomplete_results'=>false,
            'items'=>$tag_select['data']
        );
        echo json_encode($result);
    }

 public function search_tag_page($title,$have_chose_ids,$page,$page_size=30){
        $result=array();
        if(empty($title)) return $result;
        $this->load->model("tag_db");
        $have_chose_ids=trim($have_chose_ids,",");
        $tag_select=$this->tag_db->get_tag_list($title,$have_chose_ids,$page,$page_size);
        $tag_select['data']=isset($tag_select['data'])&&!empty($tag_select['data'])?$tag_select['data']:array();
        $tag_select['total']=isset($tag_select['total'])&&!empty($tag_select['total'])?$tag_select['total']:0;
        foreach($tag_select['data'] as $key=>&$val){
            $val=array(
                'id'=>$val['id'],
                'text'=>$val['name']
            );
        }
        return $tag_select;
    }

你可能感兴趣的:(jQuery插件使用)