在我的控制器中,我有以下内容:
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'));
}
这可能吗?
答案 0 :(得分:1)
您可能想要自定义回复:
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()
{
//
}
}
config/app.php
中的提供商列表:'providers' => [
'App\Providers\ResponseMacroServiceProvider',
];
return Response::smart('questions.index', $data);
答案 1 :(得分:1)
只需在索引方法本身检查Request是否为Ajax请求。
public method index() {
$questions = Question::all();
if(\Request::ajax())
return \Response::json($questions);
else
return view('questions.index', compact('questions'));
}
答案 2 :(得分:0)
使用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请求/响应的任何信息。
答案 3 :(得分:0)
我想简单的方法只是将一个方法放在父Controller类中:
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);