Skip to content

Commit 3c09a3f

Browse files
committed
新增配置默认输出格式
修复在JSONP请求下不响应输出的BUG
1 parent d2a523e commit 3c09a3f

File tree

1 file changed

+16
-8
lines changed
  • application/common/controller

1 file changed

+16
-8
lines changed

application/common/controller/Api.php

+16-8
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,12 @@ class Api
5454
*/
5555
protected $auth = null;
5656

57+
/**
58+
* 默认响应输出类型,支持json/xml
59+
* @var string
60+
*/
61+
protected $responseType = 'json';
62+
5763
/**
5864
* 构造方法
5965
* @access public
@@ -145,7 +151,7 @@ protected function loadlang($name)
145151
* @param string $type 输出类型
146152
* @param array $header 发送的 Header 信息
147153
*/
148-
protected function success($msg = '', $data = null, $code = 1, $type = 'json', array $header = [])
154+
protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
149155
{
150156
$this->result($msg, $data, $code, $type, $header);
151157
}
@@ -158,7 +164,7 @@ protected function success($msg = '', $data = null, $code = 1, $type = 'json', a
158164
* @param string $type 输出类型
159165
* @param array $header 发送的 Header 信息
160166
*/
161-
protected function error($msg = '', $data = null, $code = 0, $type = 'json', array $header = [])
167+
protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
162168
{
163169
$this->result($msg, $data, $code, $type, $header);
164170
}
@@ -168,32 +174,34 @@ protected function error($msg = '', $data = null, $code = 0, $type = 'json', arr
168174
* @access protected
169175
* @param mixed $msg 提示信息
170176
* @param mixed $data 要返回的数据
171-
* @param int $code 返回的 code
172-
* @param string $type 返回数据格式
177+
* @param int $code 错误码,默认为0
178+
* @param string $type 输出类型,支持json/xml/jsonp
173179
* @param array $header 发送的 Header 信息
174180
* @return void
175181
* @throws HttpResponseException
176182
*/
177-
protected function result($msg, $data = null, $code = 0, $type = 'json', array $header = [])
183+
protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
178184
{
179185
$result = [
180186
'code' => $code,
181187
'msg' => $msg,
182188
'time' => Request::instance()->server('REQUEST_TIME'),
183189
'data' => $data,
184190
];
185-
$type = $type ?: $this->getResponseType();
191+
// 如果未设置类型则自动判断
192+
$type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
193+
186194
if (isset($header['statuscode']))
187195
{
188196
$code = $header['statuscode'];
189197
unset($header['statuscode']);
190198
}
191199
else
192200
{
193-
$code = $code >= 1000 ? 200 : $code;
201+
//未设置状态码,根据code值判断
202+
$code = $code >= 1000 || $code < 200 ? 200 : $code;
194203
}
195204
$response = Response::create($result, $type, $code)->header($header);
196-
197205
throw new HttpResponseException($response);
198206
}
199207

0 commit comments

Comments
 (0)