Yii2 ActiveController 重写action, 分页提供数据, 自定义action

1. 重写actions

public function actions()
    {
        $actions = parent::actions();
        unset($actions['index']);
        // unset($actions['delete']);
        return $actions;
    }

    public function actionIndex()
    {
        $modelClass = $this->modelClass;
        return new ActiveDataProvider(
            [
                'query' => $modelClass::find(),
                'pagination' => ['pageSize' => 5],
                'sort' => [
                     'defaultOrder' => [
                         'id' => SORT_DESC
                     ]
                ]
            ]
            );
    }
 

这里先得到所有支持的actions,可以注销掉一些,比如不提供删除,更新之类,这边index也注销,重写了index的action,使用分页的方式来提供API数据

wx.request({
      url: 'http://localhost:8080/articles',
      header: {
        'Content-Type':'application/json'
      },
      method: 'GET',
      data:{
        page:1
      },
      success:function(res) {
        // page.setData({motto:res.data.content})
        console.log(res.data)
      }
    })

客户端就支持传入page来取得具体一页的数据了。

2.自定义action

public function actionSearch(){
        return Article::find()->where(['like','title', $_POST['keyword']])->all();
    }
'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                ['class' => 'yii\rest\UrlRule',
                 'controller' => 'article',
                 'extraPatterns' =>[
                    'POST search' => 'search'
                  ]
                
                ],
                 
            ],
        ],

还需要在配置里的urlManager 里加extraPatterns

客户端就可以使用搜索了

wx.request({
      url: 'http://localhost:8080/articles/search',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      data: {
        keyword: '视频'
      },
      success: function (res) {
        console.log(res.data)
      }
    })

在Form元素的语法中,EncType表明提交数据的格式 用 Enctype 属性指定将数据回发到服务器时浏览器使用的编码类型。 例如: application/x-www-form-urlencoded: 窗体数据被编码为名称/值对。这是标准的编码格式。

 

http://www.waitingfy.com/archives/3484

 

猜你喜欢

转载自blog.csdn.net/fox64194167/article/details/80291338
今日推荐