Home  >  Article  >  Backend Development  >  php + ajax implement post like function

php + ajax implement post like function

藏色散人
藏色散人forward
2019-12-17 17:36:503515browse

Knowledge:

1. First, the page needs to load the jquery framework

2. Explanation of common ajax parameters:

①, type: data transmission method, get or post

②. url: PHP script that processes data

③. data: transmitted data index and value. The value is obtained with js. Generally, this attribute is a json string or string

④, async: The parameter is a Boolean type, the default is true, that is, asynchronous transmission, the browser is not locked

⑤, complete: The parameter is a method, the callback function after the jump script execution is completed

⑥, success: The parameter is a method, the callback function after the jump script is successfully executed

⑦, error: The parameter is a method, the callback function after the jump script fails to execute

3. After the script processing is completed, return the data required by the page, and then implement partial refresh on the front-end page according to the needs instead of jump refresh. This is the most powerful place of ajax

html code part:

<?php
$id = $_GET[&#39;id&#39;];
require_once &#39;mysqlHelper.php&#39;;
$db = new mysqlHelper(&#39;localhost&#39;,&#39;root&#39;,&#39;root&#39;,&#39;dianzan&#39;);
$sql = "select * from news where id = &#39;$id&#39;";
$news = $db->GetOneData($sql);
 
 
 
?>
<!doctype html>
<html>
<head>
<script src="jquery-1.9.1.min.js"></script>
<meta charset="UTF-8">
</head>
<body>
<h1><?php echo $news[&#39;title&#39;];?></h1>
<pre class="brush:php;toolbar:false">
<?php echo $news[&#39;content&#39;];?>
 
点赞数:

js code:

$("#btn").click(function(){
$.ajax({
url:"index.php",
type:"POST",
data:{id:<?php echo $id;?>},
async:false,
success:function(data){
if(data === false){
alert(&#39;点赞失败!&#39;);location.href=&#39;dianzan.php?id=<?php echo $id;?>&#39;;
}else{
alert(&#39;点赞成功!&#39;);$("#s").html(data);
}
}
})
})

PHP code part:

<?php
header("Content-type:text/html;charset=utf-8");
require_once &#39;mysqlHelper.php&#39;;
$db = new mysqlHelper(&#39;localhost&#39;,&#39;root&#39;,&#39;root&#39;,&#39;dianzan&#39;);
$id = $_POST[&#39;id&#39;];
$sql = "UPDATE news SET dianzan = dianzan +1 WHERE id = &#39;$id&#39;";
 
$res = $db->execSql($sql);
if($res){
$dz = $db->getOneData("select * from news where id = &#39;$id&#39;");
$dz = $dz[&#39;dianzan&#39;];
echo $dz;
}else{
return false;
}
 
 
 
 
?>

For more PHP related knowledge, please visit PHP Tutorial!

The above is the detailed content of php + ajax implement post like function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete