【问题标题】:laravel 5 return HTML or JSON depending on routelaravel 5 根据路由返回 HTML 或 JSON
【发布时间】:2015-12-10 23:10:39
【问题描述】:

我想显示不同的输出 - JSON 或 HTML。

我无法使用\Request::ajax() 功能,因为我只是收到正常请求(JSON 响应不是基于 XHR 请求)。

是否有可能通过不同的路线区分输出?例如。检查控制器是否被带有前缀“mob”的路由调用,然后根据它为输出创建一个开关?

app/Http/routes.php:

Route::group( ['prefix' => 'api'], function(  ) {

  Route::resource( 'activation', 'ActivationController' ); 
  //...
} 

Route::group( ['prefix' => 'mob'], function(  ) {

  Route::resource( 'activation', 'ActivationController' ); 
  //...
} 

app/Http/Controllers/ActivationController:

<?php namespace App\Http\Controllers;

use App\Activation;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
class ActivationController extends Controller {

public function index()
{
    $activation = Activation::all(  );

    // switch to decide which output to show, based on the routes...
    if ($prefix == "mob") {
      return response()->view('template', compact($activation)); // not sure if it works this way
    } else {          
      return response()->json($activation);
    }

}

//...

我愿意接受务实且简单的解决方案。一定不是路由解决方案,而是一种我不必更改太多代码的方式。

【问题讨论】:

  • 您可以在此question 上使用已接受的答案。只需编辑中间件,使其不检查输入中的contentType

标签: php laravel view routes laravel-5


【解决方案1】:

您可以将前缀作为参数传递,然后根据给定的前缀在操作中处理您的业务

参考号:http://laravel.com/docs/5.1/routing#route-group-prefixes

【讨论】:

    【解决方案2】:

    您可以使用接受通配符/占位符的 Request::is() 方法。 所以你可以这样做:

    if($request->is('mob/*')) {
        // do your mob response
    } else {
        // do the other response
    }
    

    如果您每次进行响应时都有这个,那么您可以编写一个自定义响应宏来处理 if 并将数据作为数组并将其作为 json 返回或将其提供给您的刀片视图。

    【讨论】:

    • 这看起来很有趣,必须尝试一下。自定义响应是我切换后的下一个意图。
    • 我收到一个错误Undefined variable: request。如何正确访问?
    • if ( \Request::is( 'mob/*' ) ) { } 成功了。我需要指定一些特殊的东西来使用$request-&gt;is()吗?
    • 在控制器方法中,您可以定义 $request 作为第一个参数,如下所示: method(Request $request, $theOtherOnes) { ... }
    猜你喜欢
    • 2016-03-13
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多