내 페이지에 "좋아요"링크가 있습니다. 사용자는 클릭하여 고대의 것을 좋아하거나 제거 할 수 있습니다. 페이지를 다시로드하지 않으려면 자연스럽게 ajax 메서드를 사용했습니다. 이것이 아약스를 처음 접한 것입니다. 링크를 처음 클릭 할 때 작동하지만 두 번째를 클릭하면 작동하지 않습니다. 두 번째로 페이지를 다시로드합니다.두 번째 클릭시 Ajax로 페이지 재로드
이유를 모르겠다. 어떤 도움을 주시겠습니까?
NB : Symfony2에서 작업하고 있습니다.
내 나뭇 가지와 JQuery와 스크립트
<a href="" class="buttonLike{{ article.id }}" style="text-decoration: none" title="{% if like == 'true' %}Retirer des coups de coeur{% else %}Votez pour ce contenu{% endif %}" data-toggle="tooltip" data-placement="top"><i class="fa fa-heart {% if like == 'true' %}text-default{% endif %}"></i> {{ article.usersLike|length }}</a>
<!-- Ajax sur les boutons Like et Favoris -->
<script type="text/javascript" src="{{ asset('assets/plugins/jquery.min.js') }}"></script>
{% if article.isPublic %}
<script>
$("a.buttonLike{{ article.id }}").click(function (e) {
e.preventDefault();
var buttonLike = $('a.buttonLike{{ article.id }}');
$.ajax({
url: '{{ path('article_like', {'id': article.id}) }}',
type: 'GET',
dataType: 'json',
success: function (data, statut) {
console.log(data);
if (data.bool == true) {
buttonLike.replaceWith("<a href='' class='buttonLike{{ article.id }}' style='text-decoration: none' title='Votez pour ce contenu' data-toggle='tooltip' data-placement='top'><i class='fa fa-heart'></i>" + data.count + "</a>");
} else {
buttonLike.replaceWith("<a href='' class='buttonLike{{ article.id }}' style='text-decoration: none' title='Retirer des coups de coeur' data-toggle='tooltip' data-placement='top'><i class='fa fa-heart text-default'></i>" + data.count + "</a>");
}
},
error: function (resultat, statut, erreur) {
alert("Une erreur s'est produite.");
}
});
});
</script>
{% endif %}
내 컨트롤러는 : 어떤 이벤트를 부착하는 첫 번째 ""태그를 대체했기 때문에
/**
* Add or delete a like
* @Security("has_role('ROLE_USER')")
* @Route("/{id}/likes", name="article_like")
* @Method("GET")
*/
public function likesAction(Article $article) {
if ($article->getIsPublic()) {
$user = $this->container->get('security.token_storage')->getToken()->getUser();
$usersLikes = $article->getUsersLike();
$countLikes = count($usersLikes);
$bool = false;
if ($countLikes != null) {
foreach ($usersLikes as $userlike) {
if ($user == $userlike) {
$em = $this->getDoctrine()->getManager();
$article->removeUsersLike($user);
$user->removeLike($article);
$em->flush();
$countLikes = $countLikes - 1;
$bool = true;
}
}
}
if ($bool == false) {
$em = $this->getDoctrine()->getManager();
$article->addUsersLike($user);
$user->addLike($article);
$em->flush();
$countLikes = $countLikes + 1;
}
$response = new JsonResponse();
return $response->setData(array('count' => $countLikes, 'user' => $user->getId(), 'userslikes' => $usersLikes, 'bool' => $bool));
} else {
throw $this->createAccessDeniedException();
}
}
감사합니다. 불행히도, 여전히 작동하지 않습니다 ... : (당신이 말하는 것을 고려해 볼 때, 아마도 "a"태그 전체가 아닌 속성을 변경해야합니다 ... – Melody
예, 가장 좋은 방법은 버튼 (DOM 요소) 전체가 아니라 변경하려는 정보. buttonLike.attr ('title', '...') .html (''+ data.count); –
대단히 감사합니다 :) – Melody