我正在使用laravel构建应用程序,并且当访问管理区域时,如果它通过Ajax访问,则它应该能够返回JSON,如果它是&#39,它应该返回HTML。 ;不是。
目前,我在所有功能中都有类似下面的内容。是否有某种钩子我可以用来确定请求是否应该返回JSON或HTML,所以我不必在每种方法中都这样做?
// if it's accessed via ajax or set the "Accepts:" header to json
if( Request::ajax() || Request::wantsJson() )
return Response::json( $inspiration );
return View::make("admin.inspirations.show")->with("inspiration", $inspiration);
答案 0 :(得分:3)
您不必在每个方法中都这样做,您可以在基本控制器上创建一个灵活的方法:
class BaseController extends Controller {
protected function makeResult($view, $data, $withs = null)
{
if( Request::ajax() || Request::wantsJson() )
return Response::json( $data );
$view = View::make("admin.inspirations.show")->with('data', $data);
if ($withs)
{
foreach ($withs as $key => $value)
{
$view->with($key, $value);
}
}
return $view;
}
}
然后你就可以在控制器中返回:
return $this->makeResult("admin.inspirations.show", $inspiration);
如果您需要向视图发送更多数据:
return $this->makeResult("admin.inspirations.show", $inspiration, ["name" => $user->name]);
答案 1 :(得分:0)
使用laravel,您可以使用Filters挂钩路线(之前和之后)。您可能需要重新考虑您的“验证”逻辑,但我认为这是最好的方法。