Laravel在javascript中的分页对象
问题描述:
我有一个索引页,我使用分页列出了一些医院。Laravel在javascript中的分页对象
我也有一个搜索栏,我可以写一个医院的名称和列表应该“实时”更新与AJAX请求。
我的问题是,我无法通过javascript重新使用laravel分页对象来创建分页。我不想通过纯JavaScript/jQuery来管理它。目前,我正在创建返回的所有对象的列表。但是,如果没有分页(所以列表可以是巨大的)
所以在我的控制器我有这个功能
public function index()
{
$hospitals = Hospital::orderBy('name')->paginate(15);
return view('admin.hospitals.show', compact('hospitals'));
}
在我看来(/admin/hospitals/show.blade.php
),我用它来创建一个分页(我想在Ajax响应再使用此)
<ul>
@foreach($tasks as $task)
<li>{{ $task->name }}</li>
@endforeach
</ul>
{{ $tasks->links() }}
这给我的这个结果
当在搜索栏中键入,这AJAX被称为
$.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
功能
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]);
}
如何将data
对象上使用->links()
在Ajax响应? 或者我应该改变我的逻辑并在ajax请求后加载特定视图?
答
->links()
方法生成HTML代码,所以你可以做的就是将它返回到它自己的变量中。
return response()->json([
'success' => true,
'hospital' => $hospital
'pagination' => $hospital->links()
]);
进行另一种方式是通过JSON返回表html和填充容器的内容与响应
return response()->json([
'success' => true,
'html' => view('hospitals.list')->render()
]);
传递'$医院 - >链接()'的JavaScript,我没工作。创建列表视图并将呈现的视图传递给js是解决方案,谢谢! – Raccoon