好吧。我在ArticleController中有此操作:
/**
* @Route("/articles/{category}/{id}", name="article")
*/
public function getArticle($category, $id)
{
$articleRepo = $this->getDoctrine()->getRepository(Article::class);
$article = $articleRepo->find($id);
$categoryRepo = $this->getDoctrine()->getRepository(ArticleCategory::class);
$categories = $categoryRepo->findAll();
$categoryId = $categoryRepo->getCategoryIdByCode($category);
$lastArticles = $articleRepo->getLimitArticles($categoryId, 3);
$nextArticle = $articleRepo->getNextArticle($categoryId, $id);
$previousArticle = $articleRepo->getPreviousArticle($categoryId, $id);
if (is_null($nextArticle)) {
$nextArticle = $articleRepo->getRandomArticle($categoryId, $id);
}
if (is_null($previousArticle)) {
$previousArticle = $articleRepo->getRandomArticle($categoryId, $id);
}
$commentForm = $this->createForm(CommentFormType::class);
$answerForm = $this->createForm(CommentFormType::class);
$commentRepo = $this->getDoctrine()->getRepository(Comment::class);
$comments = $commentRepo->getComments($id);
foreach ($comments as $comment) {
$subcomments = $commentRepo->getSubComments($comment->getId());
$comment->subComments = $subcomments;
}
return $this->render('articles/article.html.twig', [
'article' => $article,
'categories' => $categories,
'lastArticles' => $lastArticles,
'nextArticle' => $nextArticle,
'previousArticle' => $previousArticle,
'commentForm' => $commentForm->createView(),
'answerForm' => $answerForm->createView(),
'comments' => $comments
]);
}
一切正常,它返回包含所需数据的视图文件。但是现在我想将其更改为可与AJAX动态配合使用。但是我不确定该怎么做。
第一个变体:要更改此方法,以将所有数据返回给ajax调用(JSON)并用jquery填充元素。并在页面加载和有人添加新评论时调用方法。
第二种变体:创建另一个方法(第一个方法仍将呈现视图,而不是JSON响应),该方法仅获取帖子,并在有人添加新评论时使用AJAX调用,而无需在其上发送AJAX页面加载,仅当有人添加帖子时。 (但这里我将在两种方法中具有相同的逻辑)。然后将最后添加的元素的新div添加到其他div元素。
第三种变体 :?如果有人可以帮助我?
我不希望有人为我编写代码,我希望有人告诉我哪个 是在Symfony中做到这一点的正确方法。