多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
>[danger] 该组件为系统组件,在组件树中只可命名为 response ,不可修改为其他名称。 ## 响应 响应组件用来将控制器返回的数据、设置的HTTP报头发送至客户端。 | 类 | 调用 | 运行环境 | | --- | --- | --- | | mix\http\Response | app()->response | mix-httpd | | mix\http\compatible\Response | app()->response | Apache/PHP-FPM | | 门面类 | 调用 | | --- | --- | | mix\facades\Response | Response:: | ## 组件配置 App配置文件中,该组件的默认配置如下: [>> 到 GitHub 查看默认配置 <<](https://github.com/mix-php/mix/blob/v1/apps/httpd/config/http_permanent.php#L46) 参数 `defaultFormat` 全部常量明细: - mix\http\Response::FORMAT_HTML - mix\http\Response::FORMAT_JSON - mix\http\Response::FORMAT_JSONP - mix\http\Response::FORMAT_XML ## 设置响应格式 当开发API接口时,通常需要响应 `JSON`、`JSONP`、`XML` 格式,这时可在控制中指定响应格式,代码如下: ~~~ public function actionIndex() { app()->response->format = \mix\http\Response::FORMAT_JSON; return ['errcode' => 0, 'errmsg' => 'ok']; } ~~~ 也可以在App配置文件中的 `defaultFormat` 字段中定义默认的响应格式: ~~~ // 默认输出格式 'defaultFormat' => mix\http\Response::FORMAT_JSON, ~~~ ## 重定向 重定向到首页。 ~~~ Response::redirect('/'); ~~~ ## 设置 `HTTP` 状态码 设置响应的HTTP状态码为404。 ~~~ app()->response->statusCode = 404; ~~~ ## 设置 `HTTP` 报头 设置报头Content-Type为json格式utf8编码。 ~~~ Response::setHeader('Content-Type', 'application/json;charset=utf-8'); ~~~