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字段存儲(chǔ)點(diǎn)贊的ip,這樣便于判斷該ip是否已經(jīng)點(diǎn)贊過了;
我將點(diǎn)贊和踩的圖片做成兩個(gè)按鈕;具體代碼如下:
<button rel='<?php echo 文章id;?>'><img src='http://www.gepszalag.com/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.gepszalag.com/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),是在模型里面的查詢?cè)搃p是否已經(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ù)庫查詢?cè)撈恼滤缘狞c(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)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP實(shí)現(xiàn)加法驗(yàn)證碼2. CSS可以做的幾個(gè)令你嘆為觀止的實(shí)例分享3. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)4. PHP循環(huán)與分支知識(shí)點(diǎn)梳理5. PHP session反序列化漏洞超詳細(xì)講解6. jsp+servlet簡單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))7. ASP基礎(chǔ)入門第二篇(ASP基礎(chǔ)知識(shí))8. Spring注入Date類型的三種方法總結(jié)9. ASP基礎(chǔ)知識(shí)Command對(duì)象講解10. ASP動(dòng)態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗(yàn)分享
