在 ajax 中更新分页器 laravel

Update paginator laravel in ajax

我创建了一个页面,上面有一个带有分页器的 table。我 post 请求指定从数据库中插入行的输出到 table。但是,分页器仍然很旧。我应该如何更改它? 获取新页面请求或插入所有来自控制器的 HTML 代码不满足。

代码视图:

<table class="table table-bordered text-center table-hover" id="table_list">
    <thead>
        <tr>
        <th>id</th>
        </tr>
        <tr>
            <td><input type="text" class="form-control" id="id_card" value=""></td>
        </tr>
    </thead>
    <tbody>
        @if($dats)
            @foreach($dats as $data)
                <tr>
                    <td><div class="help" data-id="{{ $data['id'] }}"> {{$data['id']}}</div></td>
                </tr>
            @endforeach
        @endif
    </tbody>
</table>
{{ $dats->links() }} // After completing the ajax, the link remains old and allows you to navigate through the old table

查看Js代码:

$('#id_card').on('keyup', function(){ // search
            value = $(this).val();
            $.ajax({
                type: 'POST',
                url: '/home',
                data: {
                    search: value,
                    code: 1,
                    _token: '{{csrf_token()}}'
                },
                success: function (data) {
                    $('#table_list').empty();
                    $('#table_list').append(data);  // update table 
                     //update paginator links
                },
                error: function(data){
                    console.log(data);
                }
            })
        })

代码控制器

public function search(Request $request){
$models= Model::where('table','LIKE','%'.$request->input('search').'%')->paginate(4);
$str = "";
foreach($models as $model){
    $str .= '<tr>'.
            '<td>'. $model["id"].'</td>'.
            '</tr>';
}
print($str);
return;

}

在 Laravel 5 中,您可以通过将控制器更改为类似这样的东西来实现。

public function search(Request $request){
    $models= Model::where('table','LIKE','%'.$request->input('search').'%')->paginate(4);
    $str = "";
    foreach($models as $model){
        $str .= '<tr>'.
                '<td>'. $model["id"].'</td>'.
                '</tr>';
    }

    return response()->json([
        'rows' => $str,
        'links' => $models->render()
    ], 200);

}   

在您的 ajax 响应中,使用 $('ul.pagination').replaceWith(data.links);

呈现链接

例如

$.ajax({
    type: 'POST',
    url: '/home',
    data: {
        search: value,
        code: 1,
        _token: '{{csrf_token()}}',
        page: page
    },
    success: function (data) {
        $('#table_list').empty();
        $('#table_list').append(data.rows);  // update table 
        $('ul.pagination').replaceWith(data.links); // update links
    },
    error: function(data){
        console.log(data);
    }
});