【问题标题】:How to create a Likes button that counts the number of clicks from each visitor如何创建一个喜欢按钮来计算每个访问者的点击次数
【发布时间】:2016-08-02 17:56:43
【问题描述】:

我在this demo blog 中看到了“点赞”功能,我正在尝试创建一个类似的按钮。似乎一旦将鼠标悬停在这个心形按钮上,就会有一个“完成”类添加到包含它的 div 中,因此必须有一个 JavaScript 计算每个喜欢。我想让它在鼠标点击时为每个访问者存储每个赞(而不是更多),并在重新加载页面时记住它(所以我想也应该有一个 cookie?)。

【问题讨论】:

  • 您需要从 JS 向您的服务器发送一个请求,该请求在数据存储中记录类似内容。然后,您可以根据需要从数据存储中请求这些记录的数量。因此,您的问题过于宽泛。
  • 请向我们展示您的代码或创建一个小提琴,我们可以在其中重现您的问题并查看您的研究成果。除非你这样做,否则我们只能猜测。这不是一个一般性的讨论论坛。 --- 请参阅有关如何发布好问题的帮助!

标签: javascript jquery html css blogger


【解决方案1】:

使用 ajax 完成,无需刷新页面即可将数据存储到 DB 并同时更新值 +1

【讨论】:

    【解决方案2】:

    index.html(HTML 文件)

    <html>
    <head>
     <script src="script.js"></script>
    </head>
    <body>
      <button id="btn">Like</button>
    </body>
    </html>
    

    script.js(Javascript 文件)

    window.onload = function(){
            document.getElementById('btn').addEventListener("click",
                      function(){
                       sendLike();
                       document.getElementById("btn").disabled = true;  
                      });
    }
    
    function sendLike(){
      var xhr;
      if(window.XMLHttpRequest) xhr = new XMLHttpRequest();
      else xhr = new ActiveXObject("Microsoft.XMLHTTP");
      xhr.open("GET","like_counter.php?like=1",true);
      if (xhr.readyState == 4 && xhr.status == 200) {
        //handle what you want to do after the operation is completed here
      }
      xhr.send();
    }
    

    like_counter.php(PHP 文件)

    <?php
     if(!(isset($_GET['like'])&&$_GET['like']==1)){
       die("Access denied!");
     }
    
     //This is just a demo. On a more practical situation,
     //you would want to store the likes in a database and verify the authenticity
     //of the request to prevent Cross-Site-Request-Forgery
     session_start();
     if(!isset$_SESSION['likes']) $_SESSION['likes'] = 0;
     $_SESSION['likes'] += 1;
     echo "done";
    ?>
    

    【讨论】:

      猜你喜欢
      • 2012-09-26
      • 1970-01-01
      • 1970-01-01
      • 2018-12-14
      • 2022-10-20
      • 1970-01-01
      • 2017-11-29
      • 2020-05-30
      • 2016-02-26
      相关资源
      最近更新 更多