php實現(xiàn)無刷新點贊的方法:首先通過ajax index.php點擊按鈕;然后實現(xiàn)js反應(yīng);接著通過ajax異步提交給“sever.php”;最后通過js返回給頁面即可實現(xiàn)無刷新點贊。
推薦:《PHP視頻教程》
ajax+php+mysql實現(xiàn)無刷新點贊功能
從動態(tài)圖看出來,點擊贊的按鈕的時候,旁邊的贊數(shù)量在無刷新地增加。打開數(shù)據(jù)庫也能看到贊數(shù)量更新了。
原理就是通過ajax異步提交數(shù)據(jù)給數(shù)據(jù)庫。
首先前端頁面就是一個按鈕和贊數(shù)量。
數(shù)據(jù)庫名,test,表名zan,字段zan
ajaxindex.php
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>異步提交</title> <script src="jquery-2.1.1.min.js"></script> <script src="ajaxindex.js"></script> </head> <body> <button id="btn">贊</button> <span id="result"> <?php $con = mysql_connect("localhost","root","root"); if (!$con) { die('連接數(shù)據(jù)庫失敗,失敗原因:' . mysql_error()); } //設(shè)置數(shù)據(jù)庫字符集 mysql_query("SET NAMES UTF8"); //查詢數(shù)據(jù)庫 mysql_select_db("test", $con); $result = mysql_query("SELECT * FROM zan"); while($row = mysql_fetch_array($result)) { echo $row['zan']; } //關(guān)閉連接 mysql_close($con); ?> </span> </body> </html> ajaxindex.js $(document).ready(function(){ $("#btn").on("click",function(){ $.get("sever.php",{name:$("#btn").val()},function(data){ $("#result").text(data); }); }); });
sever.php
<?php header("Content-type:text/html;charset=utf-8"); //連接數(shù)據(jù)庫 $con = mysql_connect("localhost","root","root"); if (!$con) { die('連接數(shù)據(jù)庫失敗,失敗原因:' . mysql_error()); } //設(shè)置數(shù)據(jù)庫字符集 mysql_query("SET NAMES UTF8"); //查詢數(shù)據(jù)庫 mysql_select_db("test", $con); //更新 mysql_query("UPDATE zan SET zan = zan+1"); $result = mysql_query("SELECT * FROM zan"); if(isset($_GET['name'])){ while($row = mysql_fetch_array($result)) { echo $row['zan']; } }else{ echo "贊失??!"; } //關(guān)閉連接 mysql_close($con); ?>
總體思路:
通過ajaxindex.php點擊按鈕,js反應(yīng),ajax異步提交給sever.php再通過js返回給頁面,就不用刷新了。
sever.php就是一個查詢和更新數(shù)據(jù)的,更新之后再把數(shù)據(jù)輸出給頁面。
整個demo下載:https://pan.lanzou.com/1485785