最新消息: 新版网站上线了!!!

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操作