从控制器返回到ajax调用的错误

时间:2017-10-03 09:17:06

标签: php ajax laravel laravel-5

我在我的控制器中有切换案例,我想将错误变量(即翻译文本)返回到我的ajax调用中。如何将我的错误消息返回到ajax调用?

switch (true) {
        case (($to <= $from) && ($statistics > $from)):
            $error = [trans('report.errors.combine')];
            return $error;
            break;
        case ($to <= $from):
            $error = [trans('report.errors.to_date')];
            return $error;
            break;
        case ($statistics > $from):
            $error = [trans('report.errors.statistics')];
            return $error;
            break;
        default:
            $this->generate($request);
    }

1 个答案:

答案 0 :(得分:1)

您应该使用ifelse if&amp; else的条件而不是switch case

   if(($to <= $from) && ($statistics > $from)){
        $error = [trans('report.errors.combine')];
    }
    elseif($to <= $from){
        $error = [trans('report.errors.to_date')];  
    }
    elseif($to <= $from){
        $error = [trans('report.errors.statistics')];
    }
    elseif($statistics > $from){
        $error = [trans('report.errors.statistics')];
    }
    else{
        $content = $this->generate($request);
    }

对于AJAX响应:

$res = (isset($error)) ? $error : $content;

header('Content-Type: application/json');
echo json_encode($res); exit();