yii2控制器Controller Ajax操作示例

时间:2022-11-26 10:47:33

本文实例讲述了yii2控制器Controller Ajax操作的方法。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public function actionSample()
{
if (Yii::$app->request->isAjax) {
  $data = Yii::$app->request->post();
  $searchname= explode(":", $data['searchname']);
  $searchby= explode(":", $data['searchby']);
  $searchname= $searchname[0];
  $searchby= $searchby[0];
  $search = // your logic;
  \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  return [
    'search' => $search,
    'code' => 100,
  ];
 }
}

模板调用方法

?
1
2
3
4
5
6
7
8
$.ajax({
    url: '<?php echo Yii::$app->request->baseUrl. '/supermarkets/sample' ?>',
    type: 'post',
    data: {searchname: $("#searchname").val() , searchby:$("#searchby").val()},
    success: function (data) {
     console.log(data.search);
    }
});

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。