jQuery 使用 Laravel 进行 AJAX 分页
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26758059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AJAX pagination with Laravel
提问by JasonK
I have this view called posts.blade.php
which gets included in home.blade.php
:
我有一个叫做的视图posts.blade.php
,它包含在home.blade.php
:
<div id="posts">
@foreach ($posts as $post)
<div class="list-item clearfix">
<div class="content">
<img src="{{ URL::to($post->thumbnail) }}" alt="" />
<h1>{{{ $post->title }}}</h1>
</div>
<div class="score">{{ $post->rating }}</div>
</div>
@endforeach
<div id="pagination">{{{ $posts->links() }}}</div>
</div>
When a user searches for certain posts, the controller's postSearch()
function returns a JSON response:
当用户搜索某些帖子时,控制器的postSearch()
函数会返回一个 JSON 响应:
function postSearch()
{
$posts = $posts->select(...)->where(...)->orderBy(...)->paginate(5); //Search posts
return Response::json(View::make('includes.posts', ['posts' => $posts])->render());
}
And jQuery appends the HTML on the #posts
div:
jQuery 将 HTML 附加到#posts
div 上:
$('#search').submit(function(e) {
e.preventDefault();
var form = $(this);
$.post(form.attr('action'), form.serialize(), function(data) {
$('#posts').html(data);
});
});
This works perfect. But now when I click on a pagination link, the page reloads and my search results are gone (obvious). How do I paginate these posts? I've read this, thisand thisarticle, but I don't understand how to implement it.
这工作完美。但是现在当我点击分页链接时,页面会重新加载并且我的搜索结果消失了(很明显)。我如何为这些帖子分页?我已经阅读了这篇、这篇和这篇文章,但我不明白如何实现它。
Edit
编辑
This is my jQuery for the pagination so far:
到目前为止,这是我用于分页的 jQuery:
$('#posts').on('click', '.pagination a', function(e) {
e.preventDefault();
var url = $(this).attr('href'),
page = url.split('page=')[1],
data = $('#search').serializeArray();
data.push({page: page}); // Add page variable to post data
console.log(data);
$.post($('#search').attr('action'), data, function(data) {
$('#posts').html(data['posts']);
});
});
This is data is being send when I click on a pagination link (page 2):
这是当我单击分页链接(第 2 页)时正在发送的数据:
Unfortunately nothing happens, the posts from page 1 keep showing.
不幸的是什么也没发生,第 1 页的帖子一直在显示。
采纳答案by lukasgeiter
I'm not very familiar with pagination in Laravel but judging from the links you listed it doesn't look too hard. This code is untested though...
我对 Laravel 中的分页不是很熟悉,但从您列出的链接来看,它看起来并不太难。虽然这段代码未经测试......
$('#pagination a').on('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.post(url, $('#search').serialize(), function(data){
$('#posts').html(data);
});
});
Update
更新
In case the pagination links are wrong (like the were for the OP) you have to build the url by yourself.
Just take the url you want and add ?page=#number
to it.
如果分页链接错误(就像 OP 的分页链接),您必须自己构建 url。
只需获取您想要的网址并添加?page=#number
到其中即可。
// page being the page number stripped from the original link
var url = $('#search').attr('action')+'?page='+page;
回答by Manish
I am using following js for getting data on href click.
我正在使用以下 js 获取有关 href 单击的数据。
// Your Local url
var Url = 'laraveltestproject/laravelpagination';
$('#ajaxContent').load("Url");
$('.pagination a').on('click', function(event) {
event.preventDefault();
if ($(this).attr('href') != '#') {
$('#ajaxContent').load($(this).attr('href'));
}
});
For Complete example you can visit the http://www.tutsway.com/laravel-ajax-pagination-example.php.
对于完整示例,您可以访问http://www.tutsway.com/laravel-ajax-pagination-example.php。
回答by themightysapien
I have the perfect tool for the job. Please check out this repo https://github.com/themightysapien/ajaxtable
我有完成这项工作的完美工具。请查看此 repo https://github.com/themightysapien/ajaxtable
Please read the docs it is very easy to use and is specially made for laravel. All you need to do is return your results as following example.
请阅读文档,它非常易于使用,并且是专为 laravel 设计的。您需要做的就是按照以下示例返回结果。
return Response::json(array(
'data'=> View::make('only_table_row_view', compact('collection')->render(),
'pagination'=>(string) $collection->links()
));
Required files are add
添加所需文件
<link rel="stylesheet" href="css/ajaxtable.css">
<script src="js/plugins.js"></script>
$(".yourtable").ajaxtable();
Initialize your ajax url through data-requestUrlattribute in your table. Add a id="paginationWrapper"div in your page where you want your pagination to appear.
通过表中的data-requestUrl属性初始化 ajax url 。在您希望分页显示的页面中添加一个id="paginationWrapper"div。
If you have any problem run the repo in your local server and see the source for html markups and plugin options.
如果您有任何问题,请在本地服务器中运行 repo,并查看 html 标记和插件选项的源代码。
回答by Raul Fernandez Marques
Example for post in a blog, solve paginate reload on delete button: (sinple foreach but you must give a id to panel and button and a class to button and use $post->id to define all)
在博客中发布示例,解决删除按钮上的分页重新加载:(简单的 foreach 但您必须为面板和按钮提供一个 id,并为按钮提供一个类,并使用 $post->id 来定义所有内容)
The trick at last is not call the view/controller that uses pagination() but the view change with javascript as you want.
最后的技巧不是调用使用 pagination() 的视图/控制器,而是根据需要使用 javascript 更改视图。
@foreach($posts as $post)
<div id="panel{{$post->id}}" class="panel panel-default">
<div class="panel-body">
{!! $post->content !!}
</div>
<div class="panel-footer">
<span class="label label-default"><span class="glyphicon glyphicon-time"></span> creado {{$post->created_at->diffForHumans()}}</span>
<span class="label label-default"><span class="glyphicon glyphicon-time"></span> modificado {{$post->updated_at->diffForHumans()}}</span>
<span class="label label-success">autor: {{ imagica\User::find($post->user_id)->name}}</span>
@if(Auth::user()->id === $post->user_id)
<form method="post" style="position:relative; top:-25px;">
<button class="btn btn-danger btn-sm pull-right destroy" id="{{$post->id}}" type="button" >eliminar</button>
</form>
<form action="{{ action('PostsController@edit', $post->id) }}" method="get" style="position:relative; top:-25px;">
<button class="btn btn-warning btn-sm pull-right" type="submit" >Editar</button>
{{-- {{ csrf_field() }} --}}
</form>
@endif
</div>
</div>
@endforeach
at last of the view javascript:
最后的视图javascript:
$(function(){
$(".destroy").on("click", function(){
var vid = $(this).attr("id");
var v_token = "{{csrf_token()}}";
var parametros = {_method: 'DELETE', _token: v_token};
var archivo = "http://imagica.app/posts/" + vid + "";
$.ajax({
type: "POST",
url: archivo,
data: parametros,
success: function(data){
$('#panel'+ data).hide();
location.reload();
}
});
});
});
In controller destroy function (note you send $post->id as data to ajax, it is used to define selectors to hide panel of post you delete):
在控制器销毁函数中(注意您将 $post->id 作为数据发送到 ajax,它用于定义选择器以隐藏您删除的帖子面板):
public function destroy($id)
{
$post= Post::find($id);
$article_id= $post->article_id;
$article= Article::find($article_id);
$msg = session()->flash('message', "Post eliminado.");
$post-> delete();
$data= $post->id;
return $data;
}
In javascript last function "location.reload()" is in order to charge flash message.
在 javascript 中,最后一个函数“location.reload()”是为了给 flash 消息充电。