【问题标题】:Laravel Restfull controllers and routing ajax / sync requestsLaravel Restful 控制器和路由 ajax / 异步请求
【发布时间】: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 类的更多细节:

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

【问题讨论】:

    标签: php rest laravel


    【解决方案1】:

    我在 Laravel 论坛中留下的 solution 涉及核心控制器类的扩展,以管理基于 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 }
    

    等等

    你可以找到粘贴here

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

    【讨论】:

    • 这是为我做的。我在扩展控制器方面做了一些额外的研究。原来是小菜一碟。 Laravel 让我惊叹不已。
    猜你喜欢
    • 2014-01-24
    • 2012-12-24
    • 2012-11-05
    • 2017-02-26
    • 2013-06-09
    • 2013-06-04
    • 1970-01-01
    • 2023-03-27
    • 2017-03-05
    相关资源
    最近更新 更多