Yii2 components api/controller

本文介绍了一个用于解决Yii2框架下API控制器返回JSON数据时,在低版本Internet Explorer浏览器中出现的问题的组件。该组件能自动检测浏览器类型,并在必要时将JSON数据包装为JSONP格式,以避免文件下载行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

When we wrote API, those controllers need to implement the following feature:

1. return JSON format data

2. sometimes support JSONP format data also.

3. support stupid low version IE

If we set format with Yii2, the low version IE will download the response content as a file.

Yii::$app->response->format = Response::FORMAT_JSON

  

So I wrote a component for it, any API controller just need to extend it.

 1 namespace api\components;
 2 
 3 use Yii;
 4 use yii\web\Response;
 5 
 6 class Controller extends \yii\web\Controller
 7 {
 8     protected $isLowIE;
 9     protected $callback;
10 
11     public function beforeAction($action)
12     {
13         $this->layout = false;
14         $this->callback = Yii::$app->request->get('callback', false);
15 
16         $this->isLowIE = (boolean)Yii::$app->request->get('ie', false);
17 
18         if (!$this->isLowIE && !$this->callback) {
19             Yii::$app->response->format = Response::FORMAT_JSON;
20         }
21 
22         return parent::beforeAction($action);
23     }
24 
25     /**
26      * @param \yii\base\Action $action
27      * @param mixed $result
28      * @return mixed
29      */
30     public function afterAction($action, $result)
31     {
32         $result = parent::afterAction($action, $result);
33         // your custom code here
34         if ($this->isLowIE || $this->callback) {
35             $result = json_encode($result);
36 
37             if ($this->callback) {
38                 $result = $this->callback .'('. $result .')';
39             }
40         }
41         return $result;
42     }
43 }

 

转载于:https://www.cnblogs.com/mztest/p/6729008.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值