【问题标题】:Laravel AJAX Pagination brings up rows from old dataLaravel AJAX 分页从旧数据中提取行
【发布时间】:2018-11-28 05:19:22
【问题描述】:

我有一个表格,一旦单击按钮,我想按 Z-A 字母顺序对其内容进行排序。

这没问题。起初我遇到的问题是我返回的分页链接不正确。修复了这些,所以我不再收到 404 页面了。但是现在当我单击下一页按钮时。该表只会转到旧无序数据的下一页。

我的排序函数:

 function Sorting($column, $direction)
{
    $data = $this->db->GetAll("mid"/* table */, "40" /* rows for pagination*/, true/*paginate*/, true,/*sorting*/ "$column" /* column to be sorted on*/, "$direction" /* ASC or DESc */);
    $Fields = $this->db->GetFieldnames("mid", false); // Field names for the table.
    $data->setPath("http://localhost:8000/dashboard/beheer/marketing"); // setting the correct path for the pagination otherwise an 404 error would be thrown.
    $returnview = view("Beheer.Dashboard.components.Marketing.tableLeads")->with('Leads', $data)->with('MidTableFields', $Fields)->render(); // returning it to the view.
    echo json_encode($returnview); // returning it to the Ajax call.
}

我的看法:

 <?php
  /**
  * Created by PhpStorm.
  * User: Entric
  * Date: 14-6-2018
  * Time: 15:43
  */
 ?>
 <div>
     <table class="table" id="tablemid">
         <thead>
         <tr>
             @foreach($MidTableFields as $field)
                 @if($field === 'id')
                     @php
                         $field = 'MID';
                     @endphp
                 @endif
                 <th id="{{$field}}"><a onclick="Sort(this.id)" href="# 
                 {{$field}}" id="{{$field}}">{{$field}}</a></th>
             @endforeach
         </tr>
         </thead>
         <tbody id="LeadsContentTable" style=>
         @foreach($Leads->reverse() as $lead)
             @if($lead->Actief == 1)
                 @php
                     $active = 'Ja';
                 @endphp
             @else
                  @php
                     $active = 'Nee';
                  @endphp
             @endif
             <tr class="tableRow" id="row{{$lead->id}}">
                 <td id="mid">
                      {{$lead->id}}
                 </td>
                 <td id="company">
                {{$lead->Bedrijfsnaam}}
            </td>
            <td id="contact">
                {{$lead->Contactpersoon}}
            </td>
            <td id="email">
                {{$lead->Email}}
            </td>
            <td id="tel">
                {{$lead->Telefoon}}
            </td>
            <td id="ip">
                {{$lead->IP}}
            </td>
            <td id="active">
                {{$active}}
            </td>
            <td id="note">
                {{$lead->Notitie}}
            </td>
            <td>
                <a href="#" id="{{$lead->id}}" onclick="EditLead(this.id);" data-toggle="modal"
                   data-target="#LeadModalEdit">
                    <button class="btn btn-neutral btn-icon btn-round button">
                        <i class="material-icons" style="color:rgba(223,176,0,0.79)">mode_edit</i>
                    </button>
                </a>
            </td>
            <td>
                <a href="#" id="{{$lead->id}}" onclick="GetDeleteLead(this.id);" data-toggle="modal"
                   data-target="#LeadModalDelete">
                    <button class="btn btn-neutral btn-icon btn-round button">
                        <i class="material-icons" style="color:rgba(185,14,22,0.81)">clear</i>
                    </button>
                </a>
            </td>
        </tr>
    @endforeach
    </tbody>
</table>
 </div>
 <div class="pagination">
     {{ $Leads->links("pagination::bootstrap-4")}}
 </div>

发起排序的JS函数:

 function Sort(identifier){
            let sorter = 'asc';
            if(sorter === 'asc'){
                sorter = 'desc';
            } else if(sorter === 'desc'){
                sorter = 'asc';
            }
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            $.ajax({
                url: '/SortLeads',
                type: 'GET',
                dataType: "json",
                beforeSend: function (xhr) {
                    const token = jQuery('meta[name="csrf_token"]').attr('content');
                    if (token) {
                        return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                    }
                },
                data: {id: identifier, sorter: sorter},
                success: function (data) {
                    $("#tablecont").empty();
                    $("#tablecont").append(data);
                }
            });
        }

更新

这就是我的控制器功能现在的样子。

     function Sorting($column, $direction)
{
    $data = $this->db->GetAll("mid"/* table */, "40" /* rows for pagination*/, true/*paginate*/, true,/*sorting*/"$column" /* column to be sorted on*/, "$direction" /* ASC or DESc */);
    $Fields = $this->db->GetFieldnames("mid", false); // Field names for the table.
    $paginator = $data->appends(['sort' => $direction ])->setPath("http://localhost:8000/dashboard/beheer/marketing")->links();
    $returnview = view("Beheer.Dashboard.components.Marketing.tableLeads")->with('Leads', $data)->with('MidTableFields', $Fields)->with('pager', $paginator)->render(); // returning it to the view.
    echo json_encode($returnview); // returning it to the Ajax call.
}

在我看来,我的分页器看起来像:

@if(!isset($pager))
{{ $Leads->links("pagination::bootstrap-4")}}
@elseif(isset($pager))
{{$pager}}
@endif

这会在新的分页器中加载,我知道这是另一个分页器,因为它没有使用 Bootstrap 4 进行样式设置。

分页器使用控制器中设置的选项加载。但它仍然没有显示数据..

【问题讨论】:

    标签: ajax laravel laravel-pagination


    【解决方案1】:

    这是因为{{ $Leads-&gt;links("pagination::bootstrap-4")}}根据旧参数创建链接。

    起初 $direction 参数是 'asc' 所以 Laravel 根据这些参数创建链接。您应该添加到可变方向参数。

    像这样的东西。 {{ $Leads-&gt;appends(['sort' =&gt; 'desc'])-&gt;links() }}

    ajax request 之后我不知道该怎么做。也许您只是在 sort button clickedsort button clicked 时使用新的 parameters 刷新页面

    你应该这样做

    success: function (data) {
               var rows = data.rows
               var paginator_links = data.links // you will produce this in backend
    
               $("#tablecont").empty();
               // $("#tablecont").append(data);
               $("#tablecont").append(rows);
    
               // here you will replace links
               $('.pagination').empty();
               $('.pagination').append(links);
             }
    

    【讨论】:

    • 会调查的。刚刚看到你的答案出现在我的收件箱里。我稍后会评论我的结果:) 谢谢!
    • 仅用于测试目的并在以后正确实施。我在 tableLeads 视图中将分页器设置为:{{ $Leads-&gt;appends(["sort" =&gt; 'desc'])-&gt;links("pagination::bootstrap-4")}} 仍然是相同的结果。它仍然获取旧数据并返回它的第二页。单击我的排序按钮,然后单击分页器。
    • 我知道。这就是为什么我说也许你应该刷新页面。这是因为您在页面加载后更新表格。当页面加载时,您的 php 代码将被编译。并且 {{ $Leads->appends(['sort' => 'desc'])->links() }} 这会产生带有链接的结果,其中 'sort' 是 'desc' 并且无论您使用 javascript 做什么它都保持不变.
    • 很快。这是我的建议。当您使用 ajax 加载数据时,在后端产生 {{ $Leads->appends(['sort' => 'desc'])->links() }} 这个。并将其替换在前端。不知道能不能解释一下。抱歉英语不好
    • 查看我更新的问题。我认为这是动态实现它的方法。但是它仍然不起作用..分页器确实被替换了。但是当加载另一个页面时它仍然没有显示我想要的数据..
    【解决方案2】:

    我将排序请求的请求类型更改为 GET。我将分页器的 url 更改为:domain.nl/dashboard/beheer/marketing/sortleads。

     let sorter = 'desc';
            function Sort(identifier){
                if(sorter === 'desc'){
                    sorter = 'asc';
                } else if(sorter === 'desc'){
                    sorter = 'asc';
                }
                if(identifier == "MID"){
                    identifier = "id";
                }
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });
                $.ajax({
                    url: '/dashboard/beheer/SortLeads',
                    type: 'GET',
                    dataType: "json",
                    beforeSend: function (xhr) {
                        const token = jQuery('meta[name="csrf_token"]').attr('content');
                        if (token) {
                            return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                        }
                    },
                    data: {id: identifier, sorter: sorter},
                    success: function (data) {
                        $("#tablecont").empty();
                        $("#tablecont").append(data);
                    }
                });
            }
    

    我检查了在 AjaxController 中触发 ajax 请求的函数中发送了哪些参数。

    我的 AjaxController 中的排序功能。

      public function LeadSort(){
        if(isset($_GET['id'])){
            $this->marketingController->Sorting($_GET['id'], $_GET['sorter']);
        } else {
            $paginator = \Session::get('pager');
            $arrayoptions = \Session::get('data');
            $data = $this->db->GetAll("mid", "50" , true, true, $arrayoptions['col'], $arrayoptions['dir'] );
            $Fields = \Session::get('fields');
            return view("Beheer.marketing")->with('Leads', $data)->with('MidTableFields', $Fields)->with('pager', $paginator)->render();
        }
    }
    

    在这里,我检查是否正在发送 ID。如果是这样的话。这意味着这是第一次对某些东西进行排序。 ID 是指列标题名称。因此,如果单击公司名称,它将按公司名称排序。

    我查看$_GET['id']设置了哪一列,查看$_GET['sorter']需要对哪个方向进行排序。我将这 2 个值放入 2 个会话变量中,以供以后在 MarketingController 的 Sorter 函数中使用。我生成排序后的数据并将其放入一个 html 表中,在此函数中,我还加载正在排序的表的表字段名称并加载/渲染分页器并将其放入会话变量中。

    最终我使用数据并将其呈现在视图中。它将由 Ajax Success 函数返回并附加。

    这是 MarketingController.php 的 Sorter 函数

     function Sorting($column, $direction)
    {
        $data = $this->db->GetAll("mid", "50", true, true,"$column", "$direction");
        $Fields = $this->db->GetFieldnames("mid", false);
    
        $paginator = $data->appends(['sort' => $direction ])->render("pagination::bootstrap-4");
        \Session::put('pager', $paginator);
        \Session::put('data', ["col" => $column, "dir" => $direction]);
        \Session::put('fields', $Fields);
    
    
        $returnview = view("Beheer.Dashboard.components.Marketing.tableLeads")->with('Leads', $data)->with('MidTableFields', $Fields)->with('pager', $paginator)->render(); // returning it to the view.
        echo json_encode($returnview); // returning it to the Ajax call.
    }
    

    但是如果我们想对表格进行分页呢?单击分页按钮时,不会发送任何 ID。所以它会尝试获取我在会话变量中放入的所有值。我重用它们来获取我的数据并呈现一个新视图。这将产生分页器点击的第二页或任何页面。这也将由 Ajax 成功函数附加

    此解决方案的缺点:

    我还没有弄清楚为什么以及如何解决此解决方案产生的这个问题。但现在的问题是:如果你按下例如分页器的第三个按钮。将加载正确的数据。但是分页器不会更新以使第三个按钮处于活动状态。

    Begmuhammet Kakabayev 的大量道具。帮助我,让我走上完整解决方案的正确道路!

    【讨论】:

      猜你喜欢
      • 2021-03-09
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-12
      • 2016-11-30
      • 2021-03-18
      • 2017-06-26
      相关资源
      最近更新 更多