php - Laravel Restfull Controller 和路由 ajax/sync 请求

标签 php rest laravel

我正在寻找最有效的方法来处理 ajax 请求作为使用普通表单的同步请求。据我所知,有 2 种方法可以处理例如新的订单发布请求:

选项 1: Controller 中的 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);
} 

在上述情况下,我必须在每个 Controller 中执行此检查。第二种情况解决了问题,但对我来说似乎有些矫枉过正。

选项 2:让路由器处理请求检查并根据请求分配 Controller 。

//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');
}

第二个选项在路由方面对我来说似乎更清晰,但它不是在工作负载(处理模型交互等)方面。

解决方案(思想家)

thinkers 的回答是正确的,并为我解决了它。下面是扩展 Controller 类的更多详细信息:

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

最佳答案

A solution我留在 Laravel 论坛涉及扩展核心 Controller 类来管理基于 REST 的系统的 ajax 和非 ajax 请求。无需检查路由并根据请求传输进行切换,您只需在 Controller 中添加一些函数,并以 'ajax_' 为前缀。因此,例如,您的 Controller 将具有以下功能

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

为了扩展核心 Controller 类,您必须更改 application/config/application.php 中的别名“Controller”类,然后将 Controller 类中的 $ajaxful 属性设置为 true (和 $restful 如果你想要 restuful ajax Controller 也是如此。

关于php - Laravel Restfull Controller 和路由 ajax/sync 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15784812/

相关文章:

php - 如何使用 mysql 8 docker 测试 laravel 5.6

php - Laravel 5.2 - 如何从具有不同表格格式的外部数据库复制用户数据

javascript - 访问sendBeacon发送的数据

php - HTML-PHP 登录后和登录前

javascript - 获取请求会导致不必要的页面重新加载

java - 如何将 Java 接口(interface)迁移到微服务?

php - Sentry on Laravel 4. 无密码社交认证

php - 如何在 PHP 中将 utf-8 字符串转换为 utf-16 字符串

php - Smarty 模板运行时出现非法字符串

php - Phil Sturgeon 的 REST API 总是返回 : status:0, 错误:未知方法