【问题标题】:Laravel yajra datatable: cannot retrieve the search parameter from ajax call in controllerLaravel yajra 数据表:无法从控制器中的 ajax 调用中检索搜索参数
【发布时间】:2018-11-08 13:18:25
【问题描述】:

我正在尝试借助来自here 的 yajra 数据表来构建具有自定义过滤功能的数据表:

视图中的 HTML 表格:

  <form id="search-form" class="form-inline" method="POST" role="form" action="#">


      <select id="batch" name="batch">
        <option value="">Select</option>
        <option value="22">Skill Level CBE Dec 2018</option>
        <option value="2">Batch 2</option>

      </select>

      <button class="btn  btn-primary" type="submit">Search</button>

  </form>

     <table class="table table-striped table-bordered datatable" cellspacing="0" width="100%">

                                    <thead>

                                        <tr>



                                            <th>{{ getPhrase('S/N')}}</th>

                                            <th>{{ getPhrase('Batch')}}</th>
                                            <th>{{ getPhrase('Course')}}</th>
                                            <th>{{ getPhrase('Subject')}}</th>

                                            <th>{{ getPhrase('title')}}</th>

                                            <th>{{ getPhrase('otq_marks')}}</th>
                                            <th>{{ getPhrase('cr_marks')}}</th>

                                            <th>{{ getPhrase('total')}}</th>
                                            <th>{{ getPhrase('average')}}</th>




                                        </tr>

                                    </thead>



         </table>


        @section('footer_scripts')



         @include('common.datatables', array('route'=>URL_STUDENT_EXAM_GETATTEMPTS.$user->slug, 'route_as_url' => 'TRUE'))


        @stop

至于common.datatablesdatatables.blade.php 有:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

     tableObj = $('.datatable').DataTable({
            processing: true,
            serverSide: true,
                retrieve :true,
            // cache: true,
            type: 'GET',

            ajax: {
             url: '{{ $routeValue }}',
             data: function (d) {
                 d.batch = $('#batch').val();

             }
         }



     });


    $('#search-form').on('submit', function(e) {
        tableObj.draw();
        e.preventDefault();
    });

ajax url 值 $routeValue 指的是 URL_STUDENT_EXAM_GETATTEMPTS 常量(稍后会澄清)以任何方式在视图中使用。

当我从"batch" 下拉列表中选择一个值并按下submit 按钮时,将对路由进行ajax 调用。在浏览器检查工具中,我看到ajax URL中添加了很多查询参数,我们的batch参数也在那里。现在我需要在控制器中检索 batch 参数。

关于服务器端代码:

blade 中使用的常量URL_STUDENT_EXAM_GETATTEMPTS 的值为PREFIX.'exams/student/get-exam-attempts/'

而在route.php中,路由定义为:

Route::get('exams/student/get-exam-attempts/{user_slug}/{exam_slug?}', 'StudentQuizController@getExamAttemptsData');

在控制器中我有:

public function getExamAttemptsData(Request $request,$slug, $exam_slug = '')
    {

    //body goes here 

    }

我已经使用了以下所有方法来获取控制器中的batch参数,但都是徒劳的:

$request->get('batch')
$request->query('batch')
Input::get('batch')

如何在控制器中检索batch 的值?

编辑:顺便说一句,我在控制器功能参数中使用use Illuminate\Http\Request; 作为Request $request 变量

EDIT2: 浏览器检查工具将 ajax 请求 url 显示为:

http://localhost/lcbs/exams/student/get-exam-attempts/myuser123 ?draw=2&columns%5B0%5D%5Bdata%5D=0......search%5Bregex%5D=false&批次=22&_=1541684388689。

所以你看到batch 在查询参数中。 但是在控制器内部,代码$request-&gt;getQueryString()只显示 %2Fexams%2Fstudent%2Fget-exam-attempts%2Fmyuser123

\URL::current() 显示 http://localhost/lcbs/exams/student/get-exam-attempts/myuser123

这意味着,$request 错过了完整的查询字符串。

EDIT3: @Adrian Hernandez-Lopez,我在这里粘贴 Kernel.php 的全部内容:

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,

    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],

        'api' => [
            'throttle:60,1',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

        'role' => \Zizaco\Entrust\Middleware\EntrustRole::class,
        'permission' => \Zizaco\Entrust\Middleware\EntrustPermission::class,
        'ability' => \Zizaco\Entrust\Middleware\EntrustAbility::class,
       // 'adminOrGuest' => \App\Http\Middleware\AdminOrGuestMiddleware::class,

    ];
}

【问题讨论】:

  • 当您检查控制器中的 $_GET['batch'] 超全局变量时会发生什么?我知道,这不是最好的解决方案,但您应该检查它只是为了调试。
  • @ISTI,空输出

标签: laravel datatable yajra-datatable


【解决方案1】:

看起来像?在 Route 中不是用来定义可选参数而是一个字符串:

Route::get('exams/student/get-exam-attempts/{user_slug}/{exam_slug?}', 'StudentQuizController@getExamAttemptsData');

你能不能把它改一下,看看你得到了什么?

Route::get('exams/student/get-exam-attempts/{user_slug}/{exam_slug}', 'StudentQuizController@getExamAttemptsData');

另外,您发布的查询字符串在myyser123 之后有一个空格,这也可以解释问题。

http:// localhost/lcbs/exams/student/get-exam-attempts/myuser123 ?draw=2&columns%5B0%5D%5Bdata%5D=0......search%5Bregex%5D=false&batch=22&_=1541684388689.

所以我建议检查一下 javascript 代码中的值是如何定义的

url: '{{ $routeValue }}',

【讨论】:

  • exam_slug 是一个可选参数,所以没有办法强制它。至于 myuser123 之后的空格,我在写 SO 时故意添加了它,以便链接只是变成文本而不是任何实际链接,因为链接指向 localhost 而不是任何在线站点。
  • 你能检查一下没有重定向可能正在重定向吗?其他的get参数,拖拽,列,....是否出现在Request对象中?
  • 如果有重定向,则不会显示 yajra 表。其他参数也不可用。但我发现使用\Request::getRequestUri();,我可以获得除“localhost”部分之外的整个url。从那时起,我可以通过使用&amp; 作为分隔符来explode url 字符串并获取数组中的所有参数,然后从该数组中我可以查找某个参数(即“批处理”)是否存在并且可以使用它。
  • $request-&gt;input('batch') 是否也返回空?还有,你从$request-&gt;all(); 得到什么输出?
  • $request-&gt;input('batch') 为空,var_dump($request-&gt;all()); 给出array(1) { ["/exams/student/get-exam-attempts/myuser123"]=&gt; string(0) "" }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-14
  • 2017-06-23
  • 1970-01-01
  • 1970-01-01
  • 2015-07-18
  • 2020-09-13
  • 2013-04-13
相关资源
最近更新 更多