1.首先新建test.html,在test.html中需要引入jquery.min.js,Button按钮中的onclick绑定的事件为clickCallBack()函数,clickCallBack()函数通过POST方式向指定的php传递值,callback(data)函数负责接收返回的参数信息(“收藏成功”或“请您先登录”)。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
function clickCallBack() {
console.log('button has clicked');
var url = "./collect_add.php";
var data = {
text: "链表"
};
jQuery.post(url, data, callback);
}
function callback(data) {
alert(data );
}
</script>
</head>
<body>
<button type="button" id="buttonid" onclick="clickCallBack()">绑定点击事件</button>
</body>
</html>
2.新建add.php,用来接收传递的参数信息,并做出回应(也可以不回应),包含数据库操作的相关内容,不需要的自动忽略。
<?php
session_start();
$conn = @mysqli_connect("localhost","root","root") ;//输入相应的数据库地址、用户名和密码
if(!$conn)
{
echo"数据库连接出错!";
}
$selected = mysqli_select_db($conn, "datastructure");
mysqli_set_charset($conn,"utf8");
$tp=$_SESSION["username"]; //用户名
$context=$_POST["text"];//从前端js返回的内容
if($tp=="")
{
echo "请您先登录";
}
else
{
$sql3 = "SELECT * FROM userdo WHERE username = '$tp' and content ='$context'";//SQL查询
$query3 = mysqli_query($conn,$sql3);//执行SQL语句
$row3=mysqli_fetch_array($query3,MYSQLI_ASSOC);
if($row3==null)
{
$sql4 = "INSERT INTO userdo(username,content,collected) VALUES('$tp','$context','1')";//SQL查询
mysqli_query($conn,$sql4);//执行SQL语句
}
else
{
$sql4="update userdo set collected = 1 where username='$tp' and content ='$context' ";
mysqli_query($conn,$sql4);//执行SQL语句,写入用户数据
}
echo "收藏成功";
}
?>