动作以及表单响应

动作数据表单以及工具表单的响应方法都是同一套方法。

在类中可以通过 $this->response() 获取到 Dcat\Admin\Http\JsonResponse对象并响应数据到前端

  1. return $this->response()->success('成功!');
  2. // 等同于
  3. use Dcat\Admin\Admin;
  4. use Dcat\Admin\Http\JsonResponse;
  5. return JsonResponse::make()->success('成功!');
  6. return Admin::make()->success('成功!');

如果是在控制器中使用,需要加上send方法

  1. public function index()
  2. {
  3. return JsonResponse::make()->success('成功!')->send();
  4. }

功能

下面介绍一下 JsonResponse 的主要用法

展示成功信息

此方法接收一个string类型参数

  1. $this->response()->success('成功!');

展示错误信息

此方法接收一个string类型参数

  1. $this->response()->error('出错了!');

展示警告信息

此方法接收一个string类型参数

  1. $this->response()->warning('警告');

跳转

此方法接收一个string类型参数,可以与successerrorwarning等方法同时使用

  1. $this->response()->redirect('auth/users');

跳转 (location)

1秒后自动跳转(非局部刷新),此方法接收一个string类型参数

  1. $this->response()->success('操作成功')->location('auth/users');

如果不传参则刷新当前页面

  1. $this->response()->success('操作成功')->location();

刷新当前页面

此方法可以与successerrorwarning等方法同时使用

  1. $this->response()->success('xxx')->refresh();

下载

此方法接收一个string类型参数

  1. $this->response()->download('auth/users?_export_=1');

展示确认弹窗

  1. // 成功
  2. $this->response()->alert(true)->success('...')->detail('详细内容');
  3. // 错误
  4. $this->response()->alert(true)->error('...')->detail('详细内容');
  5. // 警告
  6. $this->response()->alert(true)->warning('...')->detail('详细内容');
  7. // 提示
  8. $this->response()->alert(true)->info('...')->detail('详细内容');

返回HTML

此方法可接收一个stringRenderableHtmlable类型参数,可以与successerrorwarning等方法同时使用

{tip} 响应的HTML字符默认会被置入动作按钮元素上,如果需要自己控制,则覆写handleHtmlResponse方法即可。

  1. $this->response()->html('<a>a标签</a>');
  2. $this->response()->html(view('...'));

执行JS代码

此方法接收一个string类型参数,可以与successerrorwarning等方法同时使用

  1. $this->response()->script(
  2. <<<JS
  3. console.log('response', response, target);
  4. JS
  5. );

根据条件判断是否调用

上面所有功能接口都支持if模式,如

  1. // 如果 $condition 的值为 真,则调用 refresh 方法
  2. $this->response()->success(...)->ifRefresh($condition);
  3. $this->response()->success(...)->ifLocation($condition, 'auth/users');
  4. // $condition 也可以是闭包
  5. $this->response()->success(...)->ifRefresh(function () {
  6. return true;
  7. });