在控制器内的laravelview()函数中,这可以检测AJAX请求吗


In laravel view() function within a controller, can this detect an AJAX request

在我的控制器中,我有如下内容:

public function index()
{
    $questions = Question::all();
    return view('questions.index', compact('questions'));
}

不过,我希望我的ajax请求也能使用此路由。在这种情况下,我希望返回JSON。我正在考虑以下内容:

public function index()
{
    $questions = Question::all();
    return $this->render('questions.index', compact('questions'));
}
public function render($params)
{
    if ($this->isAjax()) {
        return Response::json($params);
    } else {
        return view('questions.index')->with($params);
    }
}

顺便说一句,我还没有测试过这些,但希望你能明白。

然而,我想知道我是否可以更改内置视图(…)功能本身,以使事情变得更轻松。所以我只保留以下内容:

public function index()
{
    $questions = Question::all();
    // this function will detect the request and deal with it
    // e.g. if header X-Requested-With=XMLHttpRequest/ isAjax()
    return view('questions.index', compact('questions'));
}

这可能吗?

您可能想要进行自定义响应:

  1. 添加ResponseServiceProvider.php

namespace App'Providers;
use Request;
use Response;
use View;
use Illuminate'Support'ServiceProvider;
class ResponseServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        Response::macro('smart', function($view, $data) {
            if (Request::ajax()) {
                return Response::json($data);
            } else {
                return View::make($view, $data);
            }
        });
    }
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

  1. 将"App''Providers''ResponseServiceProvider"添加到config/app.php中的提供商列表中:
'providers' => [
    'App'Providers'ResponseMacroServiceProvider',
];
  1. 在控制器中使用新助手:
return Response::smart('questions.index', $data);

只需在索引方法本身中检查请求是否为Ajax请求。

public method index() {
  $questions = Question::all();
  if('Request::ajax())
   return 'Response::json($questions);
  else
   return view('questions.index', compact('questions'));
}

使用Request::ajax(),或注入请求对象:

use Illuminate'Http'Request;
class Controller {
    public function index(Request $request)
    {
        $data = ['questions' => Question::all()];
        if ($request->ajax()) {
            return response()->json($data);
        } else {
            return view('questions.index')->with($data);
        }
    }
}

您的视图不应该知道任何关于HTTP请求/响应的信息。

我想简单的方法就是把一个方法放在父控制器类中:

use Illuminate'Routing'Controller as BaseController;
abstract class Controller extends BaseController {
    ...
    protected function render($view, $data)
    {
        if (Request::ajax()) {
            return Response::json($data);
        } else {
            return view($view, $data);
        }
    }
}

然后不执行view('questions.index, $data);,而是执行$this->render('questions.index', $data);