PHP+Ajax实现文章点赞功能
in Skill with 1437 Views

PHP+Ajax实现文章点赞功能

in Skill with 1438 Views

博主看到现在很多的网站都有点赞的功能,这不仅能提高网站的用户粘性,还能带动其他的用途。比如说点赞越高的越排在前面等等。

今天分享一篇文章,就是使用ajax+php+mysql实现无刷新点赞功能,具体实现方法直接放代码。

index.php:读取数据库

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>点赞</title>
    <script src="jquery-2.1.1.min.js"></script>
    <script src="index.js"></script>
</head>
<body>
    <button id="btn">赞</button>
    <span id="result">
        <?php
        $con = mysqli_connect('localhost', 'username', 'password');
        if(! $con )
        {
            die('连接失败: ' . mysqli_error($con));
        }
        mysqli_select_db($con,'jwhuang');
        mysqli_query($con,"set names utf8");
        $result = mysqli_query($con,"SELECT * FROM zan");
        while($row = mysqli_fetch_array($result))
        {
        echo $row['zan'];
        }
        mysqli_close($con)
        ?>
    </span>
</body>
</html>

server.php:写入数据库

<?php
header("Content-type:text/html;charset=utf-8");
$con = mysqli_connect('localhost', 'username', 'password');
if(! $con )
{
    die('连接失败: ' . mysqli_error($con));
}
mysqli_select_db($con,'jwhuang');
mysqli_query($con,"set names utf8");
mysqli_query($con,"UPDATE zan SET zan = zan+1");
$result = mysqli_query($con,"SELECT * FROM zan");
if(isset($_GET['name'])){
while($row = mysqli_fetch_array($result))
  {
  echo $row['zan'];
  }
}else{
    echo "赞失败!";
}
mysqli_close($con);
?>

index.js:请求数据

$(document).ready(function(){
    $("#btn").on("click",function(){
        $.get("sever.php",{name:$("#btn").val()},function(data){
            $("#result").text(data);
        });
    });
});

原文链接

如果本文对您有用的话,欢迎在下方留言评论哦~
发表评论
选择表情