2017-05-09 120 views
0

我正在创建一个网站,用户可以“喜欢”某些帖子。点击时我想将“喜欢”改为“喜欢”。以下代码实现此目标。问题是,在我刷新页面后,“喜欢”恢复为“喜欢”。有人能告诉我如何永久性地将“喜欢”改为“喜欢”吗?是否有可能在JavaScript中完成它?我不想在每篇文章中运行sql语句来检查特定用户是否为该帖子点击了“like”,因为这些语句可能会降低网站速度。喜欢在重新加载页面后喜欢恢复页面

这里是我的PHP代码:

echo"<a href="#" class="likes" id="$postid" >like</a>"; 

这里是我的javascript:

<script> 
    $(function(){ 
     $(".likes").click(function(){ 
      var postid = $(this).attr("id"); 
      if (document.getElementById(postid).innerHTML=="like") 
       document.getElementById(postid).innerHTML="liked"; 
      else 
       document.getElementById(postid).innerHTML="like"; 
</script> 

回答

1
to achieve your goal., you have to save it to the database, 
on your function, 
$(".likes").click(function(){ 
      var postid = $(this).attr("id"); 
      var like = 0; 
      if (document.getElementById(postid).innerHTML=="like") 
       document.getElementById(postid).innerHTML="liked"; 
       like = 1; 
      else 
       document.getElementById(postid).innerHTML="like"; 
       like = 0; 

      $.ajax{ 
        type: POST 
        data: { 'like': like, 'postid': id} 
        url: url to save your query 
        ----------etc 
      } 

}); 

create an ajax post and save it to your database, 
that's the only way you it wont disappear, 
+0

你的意思,我要跟踪哪些用户 “喜欢” 哪个职位?根据用户的不同,帖子可能会显示为“喜欢”按钮或“喜欢”按钮,所以我想知道是否必须将用户ID发送到数据库。 – gravition

+0

是的,你必须跟踪喜欢帖子的用户,以避免滥用类似按钮,并打开不同的浏览器来反复喜欢相同的帖子, – apelidoko

+0

是的,你必须保存喜欢的用户的用户名发布,就像在脸书上,在哪里我们可以看到谁喜欢某个帖子, – apelidoko