lyaui+thinkphp5评论点赞取消连贯
效果如图
数据表设计
前端JS代码
var form =layui.form,
jq =layui.jquery;
jq('span[type=zan]').click(function() {
var idnum = jq(this).data('id');
console.log(idnum);
var obj = jq(this);
//type=2,评论点赞
jq.post('{:url("home/jie/zan")}', {
'zan_collect':'zan',
'id': idnum,
'type':2
}, function(data) {
if (data.code ==200) {
var intnum =parseInt(jq(obj).find('em').html());
if (data.res =='减') {
jq(obj).removeClass('zanok');
jq(obj).find('em').html(intnum -1);
}else {
jq(obj).addClass('zanok');
jq(obj).find('em').html(intnum +1);
}
}else {
layer.msg(data.msg);
}
});
});
html中
在控制器中代码
public function zan()
{
$d = $this->request->param();
$sid = session('sid');
$tid = session('tid');
// $this->isLogin(); //判断是否登陆,测试时关闭
$cid=$d['id'];
$type=$d['type'];
$msgsubject = '';
//where('name|title','like','thinkphp%')
$com=Db::name('comment')->where('id',$cid)->select();
/* */
$insertdata=[
'sid'=>$sid,
'tid'=>$tid,
'type'=>$type,
];
$n = Db::name('zan')->where($insertdata)->find();
//如果没有点过赞
if(empty($n)){
$insertdata['time'] = time();
if (Db::name('zan')->insert($insertdata)) {
//评论表zan字段+1
Db::name('comment')->where('id', $cid)->setInc('zan');
return json(array('code' => 200, 'res' => '加', 'msg' => $msgsubject . '成功'));
} else {
return json(array('code' => 0, 'res' => '加', 'msg' => $msgsubject . '失败'));
}
}
else{
if (Db::name('zan')->where('id', $n['id'])->delete()) {
//评论表zan字段-1
Db::name('comment')->where('id', $cid)->setDec('zan');
return json(array('code' => 200, 'res' => '减', 'msg' => $msgsubject . '成功'));
} else {
return json(array('code' => 0, 'res' => '减', 'msg' => $msgsubject . '失败'));
}
}
}