php+js實(shí)現(xiàn)點(diǎn)贊功能的示例詳解
最近在做一個(gè)視頻網(wǎng)站,需要實(shí)現(xiàn)視頻的點(diǎn)贊功能,我是結(jié)合ajax和數(shù)據(jù)庫實(shí)現(xiàn)的,數(shù)據(jù)庫的格式為有四個(gè)字段:文章id,贊,踩,ip。因?yàn)樾枰粋€(gè)ip只能點(diǎn)贊一次,所以需要一個(gè)ip字段存儲點(diǎn)贊的ip,這樣便于判斷該ip是否已經(jīng)點(diǎn)贊過了;
我將點(diǎn)贊和踩的圖片做成兩個(gè)按鈕;具體代碼如下:
<button rel='<?php echo 文章id;?>'><img src='http://www.cgvv.com.cn/bcjs/點(diǎn)贊圖片路徑' alt='贊'><span style='position:absolute;margin-top:6px;margin-left:2px;font-size:20px'><span style='position:absolute;margin-top:-2px;margin-left:6px;font-size:20px'><?php if(!$vnum){echo 0;}else{ echo 點(diǎn)贊次數(shù);} ?></span></button>
<button rel='<?php echo 文章id;?>'><img src='http://www.cgvv.com.cn/bcjs/踩圖片路徑' alt='踩' ><span style='position:absolute;margin-top:2px;margin-left:6px;font-size:20px'><?php if(!$dnum){echo 0;}else{ echo 踩次數(shù);} ?></span></button>
js程序
<script type='text/javascript'>$(function(){var id=$('#vote').attr(’rel’);//獲取到文章id;$('#vote').click(function(){$.get('傳到哪個(gè)頁面?id='+id,function(r){alert(r);window.location.reload();//點(diǎn)贊成功后刷新頁面更新新的點(diǎn)贊次數(shù)})})$('#dvote').click(function(){$.get('/news/dvote?id='+id,function(r){alert(r);window.location.reload();})})})</script>
我是用ci框架寫,所以在news.php下面的vote方法和dvote方法代表的是贊和踩,具體代碼如下
public function vote(){$id=$_GET[’id’];$ip=getIP();$getdata=$this->data_model;$data=$getdata->get_vote_ip($id,$ip);$msg='';if(empty($data[’ip’]) || !$data[’ip’]){$data=array(’nid’=>$id,’vote’=>1,’ip’=>$ip);$re=$getdata->insert_vote($data);$msg.='點(diǎn)贊成功';}else{$msg.='一個(gè)ip只能操作一次';}echo $msg;}public function dvote(){$id=$_GET[’id’];$ip=getIP();$getdata=$this->data_model;$data=$getdata->get_vote_ip($id,$ip);//get_vote_ip($id,$ip),是在模型里面的查詢該ip是否已經(jīng)點(diǎn)贊過,具體代碼 如下//public function get_vote_ip($id,$ip){// $query=$this->db->query('select * from 表名 where nid=’{$id}’ and ip=’{$ip}’');// $data=$query->result_array()[0];// return $data;// }$msg='';if(empty($data[’ip’]) || !$data[’ip’]){$data=array(’nid’=>$id,’dvote’=>0,’ip’=>$ip);$re=$getdata->insert_vote($data);$msg.='踩成功';}else{$msg.='一個(gè)ip只能操作一次';}echo $msg;}
點(diǎn)贊可以實(shí)現(xiàn)以后,就是需要將點(diǎn)贊數(shù)據(jù)進(jìn)行更新,首先需要在數(shù)據(jù)庫查詢該篇文章所以的點(diǎn)贊信息
//獲取點(diǎn)贊信息public function get_vote($id){$query=$this->db->query('select * from tx_vote where nid=’{$id}’');$data=$query->result_array();return $data;}
獲取信息返回到 控制器里面將贊和踩的信息循環(huán)分別存入到數(shù)據(jù)庫中然后分別計(jì)算新的數(shù)組長度就可以獲取贊和踩的次數(shù)了,這樣的再html頁面輸出就可以了
到此這篇關(guān)于php+js實(shí)現(xiàn)點(diǎn)贊功能的示例的文章就介紹到這了,更多相關(guān)php+js實(shí)現(xiàn)點(diǎn)贊功能內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 基于 Python 實(shí)踐感知器分類算法2. Python如何批量生成和調(diào)用變量3. ASP.Net Core對USB攝像頭進(jìn)行截圖4. ajax動態(tài)加載json數(shù)據(jù)并詳細(xì)解析5. Python 中如何使用 virtualenv 管理虛擬環(huán)境6. python利用opencv實(shí)現(xiàn)顏色檢測7. 通過CSS數(shù)學(xué)函數(shù)實(shí)現(xiàn)動畫特效8. ASP.Net Core(C#)創(chuàng)建Web站點(diǎn)的實(shí)現(xiàn)9. ASP.NET MVC實(shí)現(xiàn)橫向展示購物車10. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無效問題
