doulu1325 2018-08-08 14:08
浏览 76
已采纳

Laravel Ajax分页:没有请求

I have some difficulties with my ajax pagination linked to a filter. Here's how it should work. The user can access via a specific page to a form. When clicking the submit button, a raw sql request is made in JS and a POST ajax request is achieved to get the results at the bottom of the page with a pagination menu. This part works. But I have some issues with the pagination menu because the links don't work. For example, by clicking the "page 2" link, nothing happens.

Here are the different parts of my code:

Routes

Route::get('articles/filter', 'ArticleController@filterx');
Route::post('articles/request/ajax/articles/filter', 'ArticleController@filtery');
Route::get('articles/request/ajax/articles/filter', 'ArticleController@filtery');

Controller

ArticleController

public function filterx() {   // get filter page
    return view('filter');
}

public function filtery(Request $request) {   // filter ajax function
    $articles = Article::paginate(2);
    if($request->ajax()) {
        // partial view returned in html
        return $html = view('filterResults', compact('articles'));
    }
}

Views

filter.blade.php

@extends('layouts/app')

@section('title')
    Title
@endsection

@section('content')
<div class="container">
    <!-- filter -->
    <h2>Filter</h2>
    <div class="content-card content">
        <form method="POST" action="">
            <!-- form code... -->
        </form>
    </div>
    <div id="filter-results">
    </div>
</div>
@endsection

filterResults.blade.php

@foreach($articles as $article)
    <p>{{ $article->name }}</p>
@endforeach

{{ $articles->links() }}

Javascript

$("#submit-button").click(function(e) {
    e.preventDefault();
    // ajax request (raw mysql request)
    var requestQuery = ...;    // (quite long) raw request
    console.log(requestQuery);    // console verification of request
    $.ajax({
        headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
        url: '../articles/request/ajax/articles/filter',
        type: 'POST',
        data: {
            request: requestQuery
        },
        success: function(html) {
            $("#filter-results").empty().html(html);
        }
    });
});

$(window).on('hashchange', function() {
    // if hash in url
    if (window.location.hash) {
        // page contains hash value
        var page = window.location.hash.replace('#', '');
        if (page == Number.NaN || page <= 0) {
            return false;
        }
        // if ok ->getData returned
        else {
            getData(page);
        }
    }
});

$(document).on('click', '.pagination a', function(e) {
    e.preventDefault();
    $('.pagination li').removeClass('active');
    $(this).parent('li').addClass('active');
    var url = $(this).attr('href');
    var page = $(this).attr('href').split('page=')[1];
    getData(page,url);
});

function getData(page,url) {
    $.ajax(
    {
        url: url,
        type: 'get',
        datatype: 'html',
        done: function(data) {
            console.log('ok');
            $('#filter-results').empty().html(data);
            location.hash = page;
        },
        fail: function(jqXHR, ajaxOptions, thrownError) {
            console.log('No response from server');
        }
    });
}

I don't understand why it is not working, I thing I misunderstood something.

Thanks and have a good day

  • 写回答

2条回答 默认 最新

  • dongxie9169 2018-08-08 15:03
    关注

    Laravel uses the page value from the request, or query string, by convention. If you choose not to use that, you can set your own. If following convention, you'd need to append the query string page=# to your url in the ajax request.

    The fourth argument of the Builder::paginate is the page number:

    public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
    {
        $page = $page ?: Paginator::resolveCurrentPage($pageName);
    
        $perPage = $perPage ?: $this->model->getPerPage();
    
        $results = ($total = $this->toBase()->getCountForPagination())
                                    ? $this->forPage($page, $perPage)->get($columns)
                                    : $this->model->newCollection();
    
        return $this->paginator($results, $total, $perPage, $page, [
            'path' => Paginator::resolveCurrentPath(),
            'pageName' => $pageName,
        ]);
    }
    

    You could also define your own page resolver. The default is set in PaginationServiceProvider:

        Paginator::currentPageResolver(function ($pageName = 'page') {
            $page = $this->app['request']->input($pageName);
    
            if (filter_var($page, FILTER_VALIDATE_INT) !== false && (int) $page >= 1) {
                return (int) $page;
            }
    
            return 1;
        });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵