5

我正在寻找最有效的方式来处理两个 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 类的更多细节:

  1. 在应用程序/库中创建一个 controller.php 文件。
  2. 从思想家的答案中复制控制器扩展代码。
  3. 转到 application/config/application.php 并注释此行:'Controller' => 'Laravel\Routing\Controller',
4

1 回答 1

5

我在 Laravel 论坛上留下的一个解决方案涉及扩展核心控制器类来管理基于 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 }

等等

你可以在这里找到粘贴

为了扩展核心控制器类,您必须在 application/config/application.php 中更改别名“控制器”类,然后将$ajaxful控制器类中的属性设置为 true($restful如果您想要恢复的 ajax 控制器也可以)。

于 2013-04-03T15:45:04.140 回答