Authored by wuxiao

添加jsonp返回方法

@@ -52,7 +52,7 @@ class BaseController extends Controller @@ -52,7 +52,7 @@ class BaseController extends Controller
52 */ 52 */
53 public function renderJson($code, $message, $data = '') 53 public function renderJson($code, $message, $data = '')
54 { 54 {
55 - if (is_array($data)){ 55 + if (is_array($data) || is_object($data)){
56 $retData = [ 56 $retData = [
57 'code' => (int)$code, 57 'code' => (int)$code,
58 'message' => $message, 58 'message' => $message,
@@ -77,6 +77,29 @@ class BaseController extends Controller @@ -77,6 +77,29 @@ class BaseController extends Controller
77 Yii::$app->end(); 77 Yii::$app->end();
78 } 78 }
79 79
  80 + /**
  81 + * jsonp返回
  82 + */
  83 + public function renderJsonp($data, $callback = null)
  84 + {
  85 + if ($callback === null){
  86 + $callback = Yii::$app->request->get('callback','callback');
  87 + }
  88 +
  89 + if (is_array($data) || is_object($data)){
  90 + $data = json_encode($data);
  91 + }elseif (is_numeric($data)){
  92 + $data = (int)$data;
  93 + }else{
  94 + $data = '"'.$data.'"';
  95 + }
  96 +
  97 + Yii::$app->response->format = \yii\web\Response::FORMAT_JSONP;
  98 + Yii::$app->response->content = sprintf('%s(%s)',$callback,$data);
  99 + Yii::$app->response->send();
  100 + Yii::$app->end();
  101 + }
  102 +
80 public function afterAction($action, $result) 103 public function afterAction($action, $result)
81 { 104 {
82 return parent::afterAction($action, $result); 105 return parent::afterAction($action, $result);