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.

 namespace api\components;

 use Yii;
use yii\web\Response; class Controller extends \yii\web\Controller
{
protected $isLowIE;
protected $callback; public function beforeAction($action)
{
$this->layout = false;
$this->callback = Yii::$app->request->get('callback', false); $this->isLowIE = (boolean)Yii::$app->request->get('ie', false); if (!$this->isLowIE && !$this->callback) {
Yii::$app->response->format = Response::FORMAT_JSON;
} return parent::beforeAction($action);
} /**
* @param \yii\base\Action $action
* @param mixed $result
* @return mixed
*/
public function afterAction($action, $result)
{
$result = parent::afterAction($action, $result);
// your custom code here
if ($this->isLowIE || $this->callback) {
$result = json_encode($result); if ($this->callback) {
$result = $this->callback .'('. $result .')';
}
}
return $result;
}
}

最新文章

  1. 异常:System.Data.EvaluateException: 未找到列[District].
  2. 【2016-10-13】【坚持学习】【Day4】【WPF】【ObservableCollection<T>】
  3. 数据库的日志数据库(_log.ldf)文件太大,如何压缩
  4. 对ASM存储管理的一些初步理解记录
  5. SQL Server 多条记录的某个字段拼接
  6. iOS上架(转)
  7. git add 之后因为没提交正确文件需要撤销
  8. springmvc(3)--数据类型转换
  9. PKUSC 模拟赛 day1 上午总结
  10. 更改mysql数据库latin1_swedish_ci为utf8
  11. IPTV中的EPG前端优化
  12. Oracle存储过程的一点使用总结
  13. win10环境下tensorflow-gpu安装
  14. VC2010工程依赖不再自动链接
  15. 为什么 kubernetes 天然适合微服务
  16. PHP实现表单提交发送邮件
  17. Eclipse导入文件识别不了jsp怎么办
  18. Visualizing the Git data model
  19. win7 vs2012/2013 编译boost 1.55
  20. 推荐一款jQueryajax插件(Ajaxify jQuery )

热门文章

  1. SQL 动态拼接SQL 语句
  2. Python开发【第五篇】:函数
  3. 实现html页面只自动跳转一次
  4. 洛谷P3258 [JLOI2014]松鼠的新家
  5. dbms_xplan的display查看执行计划
  6. spark sql 导出数据
  7. 禁止tableview 像上滑动
  8. CSS十一问——好奇心+刨根问底=CSSer
  9. Dell 笔记本触摸板网页双指滑动黑屏
  10. AD按键-矩阵按键-独立按键: