【教程】typecho评论点赞功能实现
更新:2022-06-10 访问:497
首先是在functions.php文件中添加
<?php
function themeInit($archive) {
//创建一个路由
if ($archive->request->getPathInfo() == "/getComment/dz") {
//功能处理函数
_getThumbsUp($archive);
}
}
//点赞功能
function _getThumbsUp($archive){
// 状态
$archive->response->setStatus(200);
//评论id
$_POST['coid'];
/**
* 行为
* dz 进行点赞
* ct 进行踩踏
**/
$_POST['behavior'];
//判断是否为登录 true 为已经登录
$loginState = Typecho_Widget::widget('Widget_User')->hasLogin();
if($loginState){
if(!empty($_POST['coid']) && !empty($_POST['behavior'])){
$db = Typecho_Db::get();
$prefix = $db->getPrefix();
$coid = (int)$_POST['coid'];
if (!array_key_exists('agree', $db->fetchRow($db->select()->from('table.comments')))) {
$db->query('ALTER TABLE `' . $prefix . 'comments` ADD `agree` INT(30) DEFAULT 0;');
}
//先获取当前赞
$row = $db->fetchRow($db->select('agree')->from('table.comments')->where('coid = ?', $coid));
$updateRows = $db->query($db->update('table.comments')->rows(array('agree' => (int) $row['agree'] + 1))->where('coid = ?', $coid));
if($updateRows){
$state = "success";
}else{
$state = "error";
}
}else{
$state = 'Illegal request';
}
}else{
$state = 'nologin';
}
//返回一个jsonv数据state数据
$archive->response->throwJson(array(
"state" => $state,
));
}
返回的json数据有:
## nologin 未登录
## success 成功
## Illegal request 非法请求(参数被篡改)
## error 点赞失败
function themeInit($archive)
如果有,就不用了,直接贴里面的代码
评论comments.php
文件,在合适的位置添加
<div class="t-comment-dz">
<a href="javascript:;" data-coid="<?php $comments->coid() ?>" class="dzcoid">点赞</a>
</div>
然后加上ajax
$(".dzcoid").click(function(){
var coid = $(this).data("coid");
$.ajax({
url: "<?php Helper::options()->index("/getComment/dz"); ?>",
type: "POST",
data: {
coid:coid,
behavior:'dz'
},
async: true,
dataType: "json",
success: function(data) {
if (data == null) {} else {
console.log(data);
if(data.state == 'success'){
alert("点赞成功");
}
}
},
error: function(err) {}
});
})