我正在 Laravel 8 中开发一个博客应用程序。
ArticlesController 控制器我有这个方法来显示单篇文章及其评论:
class ArticlesController extends FrontendController {
// More code
public function show($slug) {
// Single article
$article = Article::firstWhere('slug', $slug);
$old_article = Article::where('id', '<', $article->id)->orderBy('id', 'DESC')->first();
$new_article = Article::where('id', '>', $article->id)->orderBy('id', 'ASC')->first();
// Comments
$commentsQuery = Comment::where(['article_id' => $article->id, 'approved' => 1])->orderBy('id', 'desc');
$comments = $commentsQuery->paginate(10);
$comments_count = $commentsQuery->count();
return view('themes/' . $this->theme_directory . '/templates/single',
array_merge($this->data, [
'categories' => $this->article_categories,
'article' => $article,
'old_article' => $old_article,
'new_article' => $new_article,
'comments' => $comments,
'comments_count' => $comments_count,
'tagline' => $article->title,
])
);
}
}
在视图中我有这样的评论列表:
loading...
与文章相关的路线:
// Article routes
Route::get('/', [ArticlesController::class, 'index'])->name('homepage');
Route::get('/category/{category_id}', [ArticlesController::class, 'category'])->name('category');
Route::get('/author/{user_id}', [ArticlesController::class, 'author'])->name('author');
Route::get('/show/{slug}', [ArticlesController::class, 'show'])->name('show');
我想用“无限滚动”替换评论分页。
为此目的,我有:
/* Infinite comments */
function infiniteComments() {
var page = 1;
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() >= $(document).height() - $('.s-footer').height()) {
page++;
loadMoreData(page);
}
});
}
function loadMoreData(page){
var base_url = window.location.href.split('?')[0];
$.ajax({
url: `${base_url}?page=${page}`,
type: "get",
beforeSend: function() {
$('.ajax-load').show();
}
})
.done(function(data) {
if (data.html == "") {
$('.ajax-load').hide();
return;
}
$('.ajax-load').hide();
$(".infinite-scroll").append(data.html);
})
.fail(function(jqXHR, ajaxOptions, thrownError) {
console.log('The server is not responding...');
});
}
$(document).ready(function(){
infiniteComments();
});
访问 https://larablog.com/show/deserunt-qui-exeritationem?page=2 时正确显示第 2 页上的评论,Chrome 控制台显示这些500(内部服务器错误)错误:
https://larablog.com/show/deserunt-qui-exercitationem?page=65 500 (Internal Server Error) The server is not responding... https://larablog.com/show/deserunt-qui-exercitationem?page=76 500 (Internal Server Error) The server is not responding...
该错误可以追溯到到 ArticlesController 中第 70 行的错误消息 - $article = Article::firstWhere('slug', $slug):
尝试获取非对象的属性“id”。
这很奇怪,因为 $article = Article::firstWhere('slug', $slug) 在没有 Ajax 的情况下工作正常。
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
{{ $comment->body }}