thinkPHP实现基于ajax的评论回复功能
本文实例讲述了thinkPHP实现基于ajax的评论回复功能。分享给大家供大家参考,具体如下:
控制器代码:
count();//获取评论总数
$this->assign('num',$num);
$data=array();
$data=$this->getCommlist();//获取评论列表
$this->assign("commlist",$data);
$this->display('index');
}
/**
*添加评论
*/
publicfunctionaddComment(){
$data=array();
if((isset($_POST["comment"]))&&(!empty($_POST["comment"]))){
$cm=json_decode($_POST["comment"],true);//通过第二个参数true,将json字符串转化为键值对数组
$cm['create_time']=date('Y-m-dH:i:s',time());
$newcm=M('comment');
$id=$newcm->add($cm);
$cm["id"]=$id;
$data=$cm;
$num=M('comment')->count();//统计评论总数
$data['num']=$num;
}else{
$data["error"]="0";
}
echojson_encode($data);
}
/**
*递归获取评论列表
*/
protectedfunctiongetCommlist($parent_id=0,&$result=array()){
$arr=M('comment')->where("parent_id='".$parent_id."'")->order("create_timedesc")->select();
if(empty($arr)){
returnarray();
}
foreach($arras$cm){
$thisArr=&$result[];
$cm["children"]=$this->getCommlist($cm["id"],$thisArr);
$thisArr=$cm;
}
return$result;
}
}
JavaScript代码:
$(function(){
//点击提交评论内容
$('body').delegate('.comment-submit','click',function(){
varcontent=$.trim($(this).parent().prev().children("textarea").val());//根据布局结构获取当前评论内容
$(this).parent().prev().children("textarea").val("");//获取完内容后清空输入框
if(""==content){
alert("评论内容不能为空!");
}else{
varcmdata=newObject();
cmdata.parent_id=$(this).attr("parent_id");//上级评论id
cmdata.content=content;
cmdata.nickname="游客";//测试用数据
cmdata.head_pic="/Public/images/default.jpg";//测试用数据
varreplyswitch=$(this).attr("replyswitch");//获取回复开关锁属性
$.ajax({
type:"POST",
url:"/index.php/home/index/addComment",
data:{
comment:JSON.stringify(cmdata)
},
dataType:"json",
success:function(data){
if(typeof(data.error)=="undefined"){
$(".comment-reply").next().remove();//删除已存在的所有回复div
//更新评论总数
$(".comment-num").children("span").html(data.num+"条评论");
//显示新增评论
varnewli="";
if(cmdata.parent_id=="0"){
//发表的是一级评论时,添加到一级ul列表中
newli=""+data.nickname+""+data.create_time+" "+data.content+"