我对Laravel相当陌生,现在我需要在我的项目中实现ajax功能。我了解了如何通过ajax显示和创建文章,但当我需要列出它们时会出现问题。这有两个子问题。
我从ArticlesController获取了一些数据,它发送了如下所示的json响应:
{
status: "success", msg: "Hello!", articles: {…}, request: {…}}
articles:
current_page: 1
data: Array(1)
0: {id: 3, title: "Post1", body: "<p><strong>Lorem ipsum</strong> dolor sit amet, co…ctum. Duis feugiat facilisis lectus a cursus.</p>", created_at: "2019-06-18 00:23:25", updated_at: "2019-06-18 18:33:52", …}
length: 1
__proto__: Array(0)
first_page_url: "http://articleapp.test/postajax?page=1"
from: 1
last_page: 3
last_page_url: "http://articleapp.test/postajax?page=3"
next_page_url: "http://articleapp.test/postajax?page=2"
path: "http://articleapp.test/postajax"
per_page: 1
prev_page_url: null
to: 1
total: 3
__proto__: Object
msg: "Hello!"
request: {_token: "T31VK2FBVbIBG6IIOK4X4Q0r7WPTlzc7haXCwJrM", message: "bravo"}
status: "success"
__proto__: Object
}
Controller方法,该方法在接收到来自ajax函数的调用后,收集数据并将其作为json响应发送回。该数据的一部分是分页的文章记录表:
public function ajaks(Request $request){
if($request->ajax()){
$articles = Article::with('user')->paginate(1);
$response = array(
'status' => 'success',
'msg' => "Hello!",
"articles" => $articles,
"request" => $request->all(),
);
return response()->json($response);
}
}
Ajax功能是通过预定路由和csrf令牌一起发送请求,然后接收响应。从这个响应中,它构造了html,然后将其附加到我的布局刀片中的特定div中。她是ajax函数:
function ajaks(/*par*/){
let token = document.querySelector("meta[name='csrf-token']").getAttribute("content");
console.log("hit");
$.ajax({
url: '/postajax',
type: 'POST',
data: {_token: token , message: "bravo"},
dataType: 'JSON',
success: (response) => {
console.log("success");
console.log(response);
let body = "";
let html = "<div class='container'>";
let len = response.articles.data.length;
for(let i=0;i<len;i++){
html += "<div class='row' style='background-color: whitesmoke;'><div class='col-md-4 col-sm-4'><a href='/articles/"+response.articles.data[i].id+"'><img class='postCover postCoverIndex' src='/storage/images/"+response.articles.data[i].image+"'></a></div><div class='col-md-8 col-sm-8'><br>";
if(response.articles.data[i].body.length > 400){
body = response.articles.data[i].body.substring(0, 400)+"<a href='/articles/"+response.articles.data[i].id+"'>...Read more</a>";
}
else{
body = response.articles.data[i].body;
}
html += "<p>"+body+"</p>";
html += "<small class='timestamp'>Written on "+response.articles.data[i].created_at+" by "+response.articles.data[i].user.name+"</small></div></div><hr class='hrStyle'>";
}
let pagination = "<div class='container'><ul class='pagination justify-content-center'><li class='page-item'><a class='page-link' href='#'>Previous</a></li>";
for(let i=0;i<response.articles.last_page;i++){
pagination += "<li class='page-item'><a class='page-link' href='#'>"+(i+1)+"</a></li>";
}
pagination += "<li class='page-item'><a class='page-link' href='#'>Next</a></li></ul></div>";
//console.log(pagination);
html += "</div>"+"<form id='pagForm'>"+pagination+"</form>";
if(document.getElementById("maine")){
document.getElementById("maine").innerHTML = html;
}
},
error: (response) => {
console.log("error");
console.log(response);
}
});
}
接下来,我将检查ajax路由并获得第一组文章:
<?php
if(Route::getFacadeRoot()->current()->uri()=="ajax"){
?>
<script>
$(document).ready(function(){
ajaks();
});
</script>
<?php
}
?>
它在我的布局刀片里。同样分页链接只是简单的引导,它只是帮助我可视化。我的问题是我如何使用这个分页?使用ajax的正确方法是什么,因为我不能依赖于Laravel的内置分页。我是否应该将另一个ajax函数附加到分页链接上,然后再调用controller方法?当controller方法接收到这样的via请求时,如何在controller方法的分页中使用该请求?
实际上,您可以很容易地通过ajax使用Laravel的内置分页,您只需要在请求中传递页面。paginate函数将检测请求的页面并自动处理结果。
function ajaks(p){
p = typeof p === 'number' && p > 0 ? p : 1;
let token = document.querySelector("meta[name='csrf-token']").getAttribute("content");
console.log("hit");
$.ajax({
url: '/postajax',
type: 'POST',
data: {_token: token , message: "bravo", page: p},
...
正如您所指出的,您还需要捕获分页链接上的点击,停止常规的点击事件,并将其重定向到您的函数,如下所示...
$(document).on('click', '.pagination a', function(e){
e.preventDefault();
var p = $(this).attr('href').split('page=')[1];
ajaks(p);
});
这假定标准的laravel分页链接以page=x作为查询参数。您可以很容易地将其添加到现有的分页例程中,或者我的技巧通常是在我的控制器中呈现html并在我的ajax响应中传回它,如下所示...
$articles = Article::with('user')->paginate(1);
$response = array(
'status' => 'success',
'msg' => "Hello!",
"articles" => $articles,
"request" => $request->all(),
'pagination' => (string)$articles->links()
);
然后在浏览器中呈现...
$('#pagination').html(response.pagination);