php教程

超轻量级php框架startmvc

yii2控制器Controller Ajax操作示例

更新时间:2020-03-11 08:40:31 作者:startmvc
本文实例讲述了yii2控制器ControllerAjax操作的方法。分享给大家供大家参考,具体如下:public

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


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,
 ];
 }
}

模板调用方法


$.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);
 }
});

yii2 控制器 Controller Ajax