寫這篇文章時(shí)pbootCms版本是V2.0.7
pbootcms模板系統(tǒng)默認(rèn)給出了點(diǎn)贊、反對(duì)的鏈接。分別是:
{content:likeslink} 點(diǎn)贊鏈接
{content:opposelink} 反對(duì)鏈接
使用效果是,點(diǎn)擊一次,頁(yè)面刷新一下,點(diǎn)贊數(shù){content:likes}、{content:oppose}會(huì)顯示+1。
這個(gè)效果顯示比較硬。一個(gè)小功能,居然要頁(yè)面刷新,不能忍,必須改造。
當(dāng)我寫到一半的時(shí)候,發(fā)現(xiàn)原來PbootCms已經(jīng)有這個(gè)API接口了。手動(dòng)黑人問號(hào)。
那么還是用官方的吧,官方的開發(fā)文檔中并沒有給出相關(guān)文檔。
我們先來說一下這倆接口。
點(diǎn)贊鏈接:http://IP/api.php/do/likes/id/* //此處傳遞文章的ID,即{content:id}
反對(duì)鏈接:http://IP/api.php/do/oppose/id/* //此處傳遞文章的ID,即{content:id}
下面就簡(jiǎn)單啦。用點(diǎn)贊做示例:
$(document).ready(function (e) {
var url='/api.php/do/likes/id/'+{content:id};
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: {
appid: '{pboot:appid}',
timestamp: '{pboot:timestamp}',
signature: '{pboot:signature}'
},
success: function (response, status) {
if(response.code){
//獲取數(shù)據(jù)成功
//此處對(duì)頁(yè)面已經(jīng)顯示的{content:likes}+1,注意JS中需要轉(zhuǎn)換為數(shù)字,才能進(jìn)行+1,否則會(huì)是字符串拼接。
alert(response.data);
}else{
//返回錯(cuò)誤數(shù)據(jù)
alert(response.data);
}
},
error:function(xhr,status,error){
//返回?cái)?shù)據(jù)異常
alert('返回?cái)?shù)據(jù)異常!');
}
});
});
|
那么問題來了,這個(gè)是可以無限點(diǎn)贊的。根本停不下來呀...
我們應(yīng)該事先的效果是跟常規(guī)的刷新頁(yè)面效果一樣,一天只能點(diǎn)贊一次。
我們需要對(duì)API接口進(jìn)行優(yōu)化一下。
需要修改的文件路徑:apps/api/controller/DoController.php
大約在24行;看下注釋就知道啦。
我們同樣以點(diǎn)贊為例,上代碼:
// 點(diǎn)贊
public function likes()
{
if (! ! $id = request('id', 'int')) {
if(! cookie('likes_' . $id)){
$this->model->addLikes($id);
cookie('likes_' . $id, true, 86400, null, null, null, null);
json(1, '點(diǎn)贊成功');
}else{
json(0, '24小時(shí)內(nèi)只能點(diǎn)贊一次哦!');
}
} else {
json(0, '點(diǎn)贊失敗');
}
}
|
至此,24小時(shí)點(diǎn)贊一次的功能就優(yōu)化完成啦。