整理文档,搜刮出一个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); } }
思路:基本没什么难度,注意细节即可。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持金聪精品。