2016-05-31 2 views
0

내 페이지에 "좋아요"링크가 있습니다. 사용자는 클릭하여 고대의 것을 좋아하거나 제거 할 수 있습니다. 페이지를 다시로드하지 않으려면 자연스럽게 ajax 메서드를 사용했습니다. 이것이 아약스를 처음 접한 것입니다. 링크를 처음 클릭 할 때 작동하지만 두 번째를 클릭하면 작동하지 않습니다. 두 번째로 페이지를 다시로드합니다.두 번째 클릭시 Ajax로 페이지 재로드

이유를 모르겠다. 어떤 도움을 주시겠습니까?

NB : Symfony2에서 작업하고 있습니다.

내 나뭇 가지와 JQuery와 스크립트

<a href="" class="buttonLike{{ article.id }}" style="text-decoration: none" title="{% if like == 'true' %}Retirer&nbsp;des&nbsp;coups&nbsp;de&nbsp;coeur{% else %}Votez&nbsp;pour&nbsp;ce&nbsp;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&nbsp;pour&nbsp;ce&nbsp;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&nbsp;des&nbsp;coups&nbsp;de&nbsp;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(); 
    } 
} 

답변

0

이다. 그것을 해결하는 가장 빠른 방법은 다음과 같이 클릭 이벤트를 declarate하는 것입니다 : 그것은

$("a.buttonLike{{ article.id }}").on('click', function (e) { 
 
    // the rest of event code here... 
 
}

의 그!

+0

감사합니다. 불행히도, 여전히 작동하지 않습니다 ... : (당신이 말하는 것을 고려해 볼 때, 아마도 "a"태그 전체가 아닌 속성을 변경해야합니다 ... – Melody

+0

예, 가장 좋은 방법은 버튼 (DOM 요소) 전체가 아니라 변경하려는 정보. buttonLike.attr ('title', '...') .html (''+ data.count); –

+0

대단히 감사합니다 :) – Melody

0

내가 전체 "a"태그를 대체한다는 사실에 대해 발렌틴이 말한 것을 생각해보십시오. 나는 필요한 속성 만 바꾸는 작업을했습니다. 그리고 마침내 성공했습니다!

새로운 JQuery와 스크립트를 돕는

<script> 
    $("a.buttonLike{{ article.id }}").on('click', function (e) { 
     e.preventDefault(); 
     var buttonLike = $('a.buttonLike{{ article.id }}'); 
     var countLike = $('span.countLike{{ 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.attr('title', 'Votez&nbsp;pour&nbsp;ce&nbsp;contenu'); 
       } else { 
        buttonLike.attr('title', 'Retirer&nbsp;des&nbsp;coups&nbsp;de&nbsp;coeur'); 
       } 
       countLike.text(data.count); 
      }, 
      error: function (resultat, statut, erreur) { 
       alert("Une erreur s'est produite."); 
      } 
     }); 
    }); 
</script> 

감사합니다!

관련 문제