5.1 Response 响应输出 + 响应参数 + 重定向 + 文件下载
响应对象用于动态响应客户端请求,控制发送给用户的信息。通常用于输出数据给客户端或者浏览器。
Responce类不能直接实例化,必须使用Response::make()静态方式创建。建议使用系统提供的助手函数完成。
一 输出类型
输出类型 助手函数 对应的response类
HTML输出 response \think\Response
模板输出 view \think\Response\View
json输出 json \think\Response\Json
jsonp输出 jsonp \think\Response\Jsonp
XML输出 xml \think\Response\Xml
页面重定向 redirect \think\Response\Redirect
附件下载 download \think\Response\Download
二 响应参数
1)设置数据
return json()->data($data);
最后输出的数据 json_encode($data)
2)设置状态码
return json()->data($data)->code(200);
200 成功
340 缓存
500 失败
获取当前响应对象实例的状态码 getCode();
3)设置header头信息
return json()->data($data)->code()->header(['Cache-control' => 'no-cache,must-revalidate']);
获取当前响应对象实例的头信息 getHeader();
4)语法一步到位
return json($data,$code,$header);
5)写入 Cookie
response()->cookie('name','value',600);
6)设置额外参数 options()
在进行 json 输出的时候需要设置 json_encode 方法的额外参数, jsonp 输出的时候需要设置 jsonp_handler 等参数, 这些都可以使用 options 方法来进行处理,例如: jsonp($data)->options([ 'var_jsonp_handler' => 'callback', 'default_jsonp_handler' => 'jsonpReturn', 'json_encode_param' => JSON_PRETTY_PRINT, ]);
7)关闭当前请求缓存
json($data)->code(201)->allowCache(false);
8)自定义响应
如果需要特别的自定义响应输出,可以自定义一个 Response 子类,并且在控制器的操作方法中直接返回。又 或者通过设置响应参数的方式进行响应设置输出。
三 重定向
1)跳转到域名上
return redirect('http://www.baidu.com');
重定向状态码 是302 需要 return 执行
2)站内重定向
//1 直接使用完整地址( / 打头)
return redirect('/index/index/index');
//2 使用url()函数
return redirect(url('index',['id'=>10]));
3)附加 session 闪存数据重定向 with()方法
//1 跳转到当前类的 index 方法 public function demo($blogId=0){ return redirect(url('index'))->with('name','李白'); } //2 打印传递过来的session值 public function index(){ echo session('name'); }
4)记住请求地址
//1 记住当前url后跳转 return redirect('index')->remember(); //2 跳转到上次记住的url return redirect()->with('name','Li_bai')->restore();
举例:
<?php namespace app\admin\controller; use think\facade\Request; class Demo { //执行页面 public function demo(){ if (session('?name')) { echo session('name'); } else{ return redirect('index')->remember(); } } //跳转页面 public function index(){ $url = url('back'); echo "<a href='{$url}'>跳转</a>"; } //跳回demo页面 public function back(){ return redirect()->with('name','Li_bai')->restore(); } }
四 文件下载

浙公网安备 33010602011771号