yii2使用select2,将搜索的数据分页加载

//这是model层
 public static function getUsersByKeywords ($page,$q,$offset)
    {
        $query = new Query();
        $query ->select([
            'u.user_id',
            'u.user_name'
        ])->from([
            'u' => User::tableName()
        ]);
        if (!empty($q)) {
            $query->andWhere(['like','u.user_name',$q]);
        }
        $total_count = $query->count();
        $pagination = new Pagination(['totalCount' => $total_count, 'page' => $page-1,'pageSize'=>$offset]);
        $list =  $query
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->orderBy('user_id asc')
            ->all();
        $users = $list;
        $data['users'] = $users;
        $data['total_count'] = $total_count;
        return $data;
    }
//这是控制器层
public function actionGetUsersByKeywords()
    {
        $page = Filter::get('page',1);//当前页
        $q = Filter::get('q'.'');//关键字
        $offset =  Filter::get('offset',6);//每页显示条数
        $data = shop::getUsersByKeywords($page,$q,$offset);
        return Result::success([
            'res' =>$data['users'],
            'total' => $data['total_count'],
        ])->toJson();
    }
//这是html使用了模板引擎的,加个class就行了
{fieldtemplate model=$model field='user_id'}
    {input type='select' class='js-data-example-ajax' model=$model field='user_id' items=$users}
{/fieldtemplate}
//这是js
{script src='@static/js/select2/select2.min.js'}
//引入css
{link href="@static/css/select2/select2.min.css"}






你可能感兴趣的:(yii2使用select2,将搜索的数据分页加载)