我有一个索引页,我在其中列出了一些医院的分页。
我还有一个搜索栏,我可以在这里写一个医院名称,清单应该用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]);
}如何在ajax响应中对->links()对象使用data?或者我应该在ajax请求之后更改我的逻辑并加载一个特定的视图?
发布于 2017-10-20 16:48:51
->links()方法生成HTML代码,所以您可以做的是在它自己的变量中返回它。
return response()->json([
'success' => true,
'hospital' => $hospital
'pagination' => $hospital->links()
]);进行下去的其他方法是通过JSON返回表html并用响应填充容器的内容
return response()->json([
'success' => true,
'html' => view('hospitals.list')->render()
]);https://stackoverflow.com/questions/46852278
复制相似问题