nauhein
- nauhein 2018-09-20 已签到连续签到4天,获得了20个金钱
- nauhein 赞了回答
你代码中的配置仅对正常的网页请求,ajax 请求的个性化错误信息可通过配置
response
组件实现。你遇到的 500 错误是因为 response 组件在遇到错误时,直接把错误传递到客户端并被 jQuery 捕获。可以借助 Response 的 beforeSend 事件改变这种默认的行为:在发送错误前将错误信息进行封装,
'components' => [ 'response' => [ 'class' => 'yii\web\Response', 'on beforeSend' => function ($event) { $response = $event->sender; // 这里我们仅针对 ajax 请求 if ($response->format == \yii\web\Response::FORMAT_JSON) { if ($response->data !== null) { // 手动将抛出异常的状态码改为 200, 确保不被 jQuery 捕获 $response->statusCode = 200; // 自定义错误显示格式,把真正的响应数据存储在 'data' option 内 $response->data = [ 'success' => $response->isSuccessful, 'data' => $response->data, ]; } } }, ], ],
配置后,如果通过 ajax 访问下面的 action,
// in TestController.php public function actionAjaxRead() { Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; // 这里将抛出异常 return 3/0; }
$.post("/test/ajax-read", function(response) { console.log(response) })
响应内容将输出:
参考: https://www.yiiframework.com/doc/guide/2.0/zh-cn/runtime-handling-errors#error-format
原生语句
$params = [':name' => $name];
$result = Yii::$app->db->createCommand('SELECT * FROM {{%auth_item}} WHERE name=:name ')->bindValues($params)->queryAll();
- nauhein 2018-09-19 已签到连续签到3天,获得了15个金钱
- nauhein 2018-09-18 已签到连续签到2天,获得了10个金钱
- nauhein 2018-09-17 已签到连续签到1天,获得了5个金钱
- nauhein 2018-09-14 已签到连续签到2天,获得了10个金钱
- nauhein 2018-09-13 已签到连续签到1天,获得了5个金钱
- nauhein 2018-09-06 已签到连续签到4天,获得了20个金钱