php結合ajax實現贊、頂、踩功能執行個體_PHP教程

來源:互聯網
上載者:User
php應用越來越多,也越來越廣泛,為了增加網站的豐富多彩,從而出現了很多新的技術。ajax是現代網站中不能缺少的一項技術,他可以非同步重新整理資料,而實現很多效果,比如重新整理驗證碼,微博中的贊功能,都是運用這個。

本次贊功能的:

首頁檔案(index.php):
複製代碼 代碼如下:


header("Content-type:text/html;charset=utf-8");
include "finger_ajax.php";

$sql = "select * from finger_ajax";
$res = mysql_query($sql,$link);
while($row = mysql_fetch_array($res)){
echo "

".$row['title']." \r\n贊一下(".$row['finger'].")

\r\n";
}
?>

處理ajax請求及配置資訊檔(finger_ajax.php):
複製代碼 代碼如下:
/**"贊" 功能 響應ajax請求*/
//配置
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "dddddd";
$dbName = "test";
$dbCharset = "utf8";

$link = mysql_connect($dbHost,$dbUser,$dbPass) or die(mysql_error());
mysql_query("set names ".$dbCharset);
mysql_select_db($dbName);
// End

//接受對應的id
if(!empty($_POST['id'])){
$id = $_POST['id'];
//“贊”加1
$sql = "update finger_ajax set finger=finger+1 where id=$id;";
if(mysql_query($sql,$link)){
echo "ok";
}else{
echo "failed";
}
}
?>


js檔案(finger_ajax.js):
複製代碼 代碼如下:
//贊 js
function finger(topic_id){
$.post("finger_ajax.php", { "id": topic_id },
function(data){
if(data=="ok"){
alert("感謝您的支援!");
}else{
alert("對不起,失敗了!");
}
}, "text");
//擷取當前“贊”的次數並加1
var finger = parseInt($(".finger"+topic_id).html())+1;
//更新“贊”的次數
$(".finger"+topic_id).html(finger);
}

資料庫代碼(finger_ajax.sql):
複製代碼 代碼如下:
DROP TABLE IF EXISTS `finger_ajax`;
CREATE TABLE `finger_ajax` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(50) NOT NULL DEFAULT '',
`finger` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of finger_ajax
-- ----------------------------
INSERT INTO `finger_ajax` VALUES ('1', '今天天氣還不錯哦!去做點什麼好呢?', '10');
INSERT INTO `finger_ajax` VALUES ('2', '歡迎來到 www.jb51.net,國慶將至,祝大家國慶節快樂!!', '3');

http://www.bkjia.com/PHPjc/769247.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/769247.htmlTechArticlephp應用越來越多,也越來越廣泛,為了增加網站的豐富多彩,從而出現了很多新的技術。ajax是現代網站中不能缺少的一項技術,他可以非同步...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.