【发布时间】:2013-03-24 23:15:49
【问题描述】:
我正在寻找最有效的方法来使用普通形式将 ajax 请求作为同步请求来处理。据我所知,有两种方法可以处理例如新订单发布请求:
选项 1:AJAX 检查控制器(为简单起见,省略了验证和保存)。
//Check if we are handling an ajax call. If it is an ajax call: return response
//If it's a sync request redirect back to the overview
if (Request::ajax()) {
return json_encode($order);
} elseif ($order) {
return Redirect::to('orders/overview');
} else {
return Redirect::to('orders/new')->with_input()->with_errors($validation);
}
在上述情况下,我必须在每个控制器中进行此检查。第二种情况解决了问题,但对我来说似乎有点矫枉过正。
选项 2:让路由器处理请求检查并根据请求分配控制器。
//Assign a special restful AJAX controller to handle ajax request send by (for example) Backbone. The AJAX controllers always show JSON and the normal controllers always redirect like in the old days.
if (Request::ajax()) {
Route::post('orders', 'ajax.orders@create');
Route::put('orders/(:any)', 'ajax.orders@update');
Route::delete('orders/(:any)', 'ajax.orders@destroy');
} else {
Route::post('orders', 'orders@create');
Route::put('orders/(:any)', 'orders@update');
Route::delete('orders/(:any)', 'orders@destroy');
}
就路由而言,第二个选项对我来说似乎更清晰,但就工作量(处理模型交互等)而言却不是。
解决方案(由思想家提出)
思想家的答案很准确,并为我解决了。下面是扩展 Controller 类的更多细节:
- 在应用程序/库中创建一个 controller.php 文件。
- 从thinkers answer中复制Controller扩展代码。
- 转到 application/config/application.php 并注释此行: '控制器' => 'Laravel\Routing\Controller',
【问题讨论】: