我正在寻找使用普通表单将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);
}
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,我必须在每个控制器中进行检查.第二种情况解决了这个问题,但对我来说这看起来有些过分.
选项2:让路由器根据请求处理请求检查和asign控制器.
//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');
}
Run Code Online (Sandbox Code Playgroud)
在路由方面,第二个选项对我来说似乎更干净,但它不是在工作负载方面(处理模型交互等).
解决方案(由思想家提供)
思想家的回答是现场,并为我解决了.下面是扩展Controller类的更多细节:
我在Laravel论坛中留下的解决方案涉及扩展Core控制器类,以管理基于REST的系统的ajax和非ajax请求.您可以在控制器中添加一些函数,而不是检查路由并根据请求传输进行切换'ajax_'.因此,例如,您的控制器将具有这些功能
public function get_orders() { will return results of non-ajax GET request}
public function ajax_get_orders() { will return results of ajax GET request }
public function post_orders() {will return results of non-ajax POST request }
public function ajax_post_orders() { will return results of ajax POST request }
Run Code Online (Sandbox Code Playgroud)
等等
你可以在这里找到粘贴
为了扩展Core Controller类,你必须在application/config/application.php中更改别名'Controller'类,然后将$ajaxful控制器类中的属性设置为true($restful如果你想要restuful ajax控制器).
| 归档时间: |
|
| 查看次数: |
2805 次 |
| 最近记录: |