整理文档,搜刮出一个PHP 实现收藏功能的示例代码,稍微整理精简一下做下分享。
HTML:
取消收藏
收藏
Js:
获取图片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:
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);
}
}
思路:基本没什么难度,注意细节即可。