php 实现收藏功能的示例代码
整理文档,搜刮出一个php 实现收藏功能的示例代码,稍微整理精简一下做下分享。
HTML:
<a class = "x" id="{$photo.id}" uid="{$Think.session.uid}" status = "{$collect_pic}" href = "javascript:void(0);"> <if condition = "$collect_num gt 0"> <span>取消收藏</span> <else/><span>收藏</span></if></a>
Js:
//点击收藏,实现已收藏 $('.x').on('click',function(){ var Oa=$(this); var id=Oa.attr('id');//获取图片id属性 var uid = Oa.attr('uid');//获取用户id var status = Oa.attr('status'); //获取收藏状态 1收藏,0取消收藏 $.post('url',{id:id,uid:uid,status:status},function(msg){ if(msg.status==1){ Oa.find("span").text('取消收藏'); Oa.attr('status','1'); }else{ Oa.find("span").text('收藏'); Oa.attr('status','0'); } },'json') })
PHP:
//判断用户是否已收藏该图片 $data['uid'] = $_SESSION['uid']; $data['pid'] = $pid; $collect_pic = M('collect')->where($data)->getfield('status'); $this->collect_num = $collect_num; $this->collect_pic = $collect_pic; //收藏成功 public function cang(){ $data['pid'] = isset($_POST['id'])?intval(trim($_POST['id'])):0; $data['uid'] = $_SESSION['uid']; //默认o收藏 1取消收藏 $status = isset($_POST['status'])?intval(trim($_POST['status'])):0; $db = M('collect'); if($status == 0){ //数据组装,忽略 if(M('collect')->data($collect)->add()){ $msg['info'] = "ok"; $msg['status'] = 1; $this->ajaxreturn($msg); exit; }else{ $msg['info'] = 'fail'; $msg['status'] = 1; $this->ajaxreturn($msg); } }else{ //取消收藏 if($db->where($data)->delete()){ $msg['info'] = "ok"; $msg['status'] = 0; $this->ajaxreturn($msg); exit; }else{ $msg['info'] = 'fail'; $msg['status'] = 0; $this->ajaxreturn($msg); } }
思路:基本没什么难度,注意细节即可。
相关推荐
zyyjay 2020-11-09
xuebingnan 2020-11-05
samtrue 2020-11-22
stefan0 2020-11-22
yifangs 2020-10-13
songshijiazuaa 2020-09-24
hebiwtc 2020-09-18
天步 2020-09-17
83911535 2020-11-13
whatsyourname 2020-11-13
zhouyuqi 2020-11-10
Noneyes 2020-11-10
mathchao 2020-10-28
王志龙 2020-10-28
wwwsurfphpseocom 2020-10-28
diskingchuan 2020-10-23
savorTheFlavor 2020-10-23