Laravel yajra 数据表:无法从控制器中的 ajax 调用中检索搜索参数 [英] Laravel yajra datatable: cannot retrieve the search parameter from ajax call in controller

查看:21
本文介绍了Laravel yajra 数据表:无法从控制器中的 ajax 调用中检索搜索参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to build a dataTable with custom filtering with the help of yajra datatable from here :

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 常量(稍后澄清).

ajax url value $routeValue refers to URL_STUDENT_EXAM_GETATTEMPTS constant (to be clarified later) used in view in whatever way.

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

When I select a value from the "batch" drop-down and press the submit button, an ajax call is made to the route. In browser inspection tool, I see that a lot of query parameters are added in the ajax URL and our batch param is also there. Now I need to retrieve that batch parameter inside the controller.

现在关于服务器端代码:

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

The constant URL_STUDENT_EXAM_GETATTEMPTS used in blade has the value 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 参数,但没有成功:

I have used all the following methods to get the batch parameter in the controller but in vain :

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

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

How can I retrieve the value of batch inside the controller ?

顺便说一句,我正在使用 use IlluminateHttpRequest; 作为控制器函数参数中的 Request $request 变量

BTW I am using use IlluminateHttpRequest; for the Request $request variable in controller function parameter

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

The browser inspection tool shows the ajax request url as :

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

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

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

So you see that batch is there in the query parameters. But inside the controller, the code $request->getQueryString() only shows %2Fexams%2Fstudent%2Fget-exam-attempts%2Fmyuser123

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

And URL::current() shows http:// localhost/lcbs/exams/student/get-exam-attempts/myuser123

这意味着,$request 遗漏了完整的查询字符串.

That means, the $request misses the complete query string.

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

@ Adrian Hernandez-Lopez, I am pasting the FULL content of Kernel.php here :

namespace AppHttp;

use IlluminateFoundationHttpKernel 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 = [
        IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode::class,

    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            AppHttpMiddlewareEncryptCookies::class,
            IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
            IlluminateSessionMiddlewareStartSession::class,
            IlluminateViewMiddlewareShareErrorsFromSession::class,
            AppHttpMiddlewareVerifyCsrfToken::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' => AppHttpMiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'can' => IlluminateFoundationHttpMiddlewareAuthorize::class,
        'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,

        'role' => izacoEntrustMiddlewareEntrustRole::class,
        'permission' => izacoEntrustMiddlewareEntrustPermission::class,
        'ability' => izacoEntrustMiddlewareEntrustAbility::class,
       // 'adminOrGuest' => AppHttpMiddlewareAdminOrGuestMiddleware::class,

    ];
}

推荐答案

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

Looks like the ? in the Route is not used to define an optional parameter but a string instead:

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

能否请您更改一下,看看您会得到什么?

Could you please change it and see what you get?

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

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

Also, the query string you posted has a space after myyser123, this could also explain the issue.

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 代码中定义的

So I would suggest to check how the value is defined in the javascript code

url: '{{ $routeValue }}',

这篇关于Laravel yajra 数据表:无法从控制器中的 ajax 调用中检索搜索参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆