游.程 2017-12-16 01:38 采纳率: 0%
浏览 53

更改Yii2 API操作

I use yii2 (2.0.13). when i send data with ajax, the return response includes an error.

my code:

namespace frontend\controllers;

use Yii;
use yiiest\ActiveController;    

class CityController extends ActiveController
{
    public $modelClass = 'frontend\models\City';

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

    public function behaviors()
    {
        $behaviors = parent::behaviors();

        // remove authentication filter
        $auth = $behaviors['authenticator'];
        unset($behaviors['authenticator']);

       // add CORS filter
        $behaviors['corsFilter'] = [
            'class' => \yii\filters\Cors::className(),
        ];

        // re-add authentication filter
        $behaviors['authenticator'] = $auth;
        // avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
        $behaviors['authenticator']['except'] = ['options'];

        return $behaviors;
    }    

    public function actionCreate()
    {
      echo 'Hi i\'m create!!';
    }
}    

And ajax request:

$.ajax({
            url: "http://blog.dev/city", // our php file
            type: 'POST',
            contentType: false,
            cache: false,
            processData: false,
            data: {x: 'data_text'},
            success: function(data){
                console.log(data);
            },
            error: function (request) {
                console.log(request);
            }
        });    

When in the actionCreate I add exit() the problem is fixed.
Where is the problem and exactly how should I change actionCreate?
Help me, please.

  • 写回答

1条回答 默认 最新

  • 旧行李 2017-12-16 03:44
    关注

    The client is send a ajax request, so Yii2 should process the request like a ajax request too. You need change the code like this:

    <?php
    ...
    public function actionCreate()
    {
      if (Yii::$app->request->isAjax) {
          // DO SOMETHING
          \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
          return [
              'message' => 'Hi i\'m create!!'
          ];
      }
    }
    

    The client side you can have something like this:

    $.ajax({
       url: '<?php echo Yii::$app->request->baseUrl. '/ads' ?>',
       type: 'post',
       data: {
                  x: 'data_text', 
                 _csrf : '<?=Yii::$app->request->getCsrfToken()?>'
             },
       success: function (data) {
          console.log(data.message);
       }
    

    });

    Important! You need send the CSRF token if you have enableCsrfValidation in TRUE

    评论

报告相同问题?

悬赏问题

  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂