首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >javascript中的Laravel分页对象

javascript中的Laravel分页对象
EN

Stack Overflow用户
提问于 2017-10-20 15:21:04
回答 1查看 5.7K关注 0票数 2

我有一个索引页,我在其中列出了一些医院的分页。

我还有一个搜索栏,我可以在这里写一个医院名称,清单应该用AJAX请求“实时”更新。

我的问题是我无法通过javascript重用laravel分页对象来创建分页。我不想用纯javascript/jQuery来管理它。目前,我正在创建返回的所有对象的列表。但是没有分页(所以列表可能很大)

所以在我的控制器里我有一个函数

代码语言:javascript
复制
public function index()
{
    $hospitals = Hospital::orderBy('name')->paginate(15);
    return view('admin.hospitals.show', compact('hospitals'));
}

在我的观点(/admin/hospitals/show.blade.php)中,我使用它来创建分页(我想在ajax响应上重用它)

代码语言:javascript
复制
<ul>
@foreach($tasks as $task)
    <li>{{ $task->name }}</li>
@endforeach
</ul>
{{ $tasks->links() }}

这给了我这个结果

在搜索栏中键入时,此ajax将被调用

代码语言:javascript
复制
$.ajax({
    type: "GET",
    url: '/admin/hospitals/search/'+ $('#hospital_search').val().trim(),
    success: function (data) 
    {
        if ( data.hospital.length == 0 ) 
        {
            $('#hospital_result').html('<div class="alert alert-warning">No hospitals found</div>');
        }
        else
        {
            //Actual code that give me the listing without pagination
            //Would be nice if I could do something like {{ data.hospital->links() }}
            var html = '<ul>';
            $.each( data.hospital , function( i , hospital ){    
                html += '<li><a href="/admin/hospitals/'+ hospital.id +'"><b>' + hospital.name + '</b></a></li>';});
            html += '</ul>';
            $('#hospital_result').html(html);
        }
    },
    error: function (data) 
    {
        alert('Error:', data);
    }
});

和我的search函数

代码语言:javascript
复制
public function search($term = null)
{       
    if( !$term )
    {
        $hospital = Hospital::orderBy('name')->get();
    }
    else
    {
        //Get match on name
        $hospital = Hospital::where('name' , 'LIKE' , '%'.$term.'%')
                        ->orderBy('name')
                        ->get(); //Should be replaced by ->paginate(15) when JS will be replaced
    }

    //Return as JSON
    return response()->json(['success' => true, 'hospital' => $hospital]);
}

如何在ajax响应中对->links()对象使用data?或者我应该在ajax请求之后更改我的逻辑并加载一个特定的视图?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-20 16:48:51

->links()方法生成HTML代码,所以您可以做的是在它自己的变量中返回它。

代码语言:javascript
复制
return response()->json([
    'success' => true,
    'hospital' => $hospital
    'pagination' => $hospital->links()
]);

进行下去的其他方法是通过JSON返回表html并用响应填充容器的内容

代码语言:javascript
复制
return response()->json([
    'success' => true, 
    'html' => view('hospitals.list')->render()
]);
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46852278

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档