PHP Unlimited Classification Combat--Comment and reply function _php Tutorial

Source: Internet
Author: User

PHP Unlimited Classification Combat--Comment and reply function


Often in the major forums or the news section of the details page to see the comment function, of course, not only directly post comments so simple, you can reply to other people's comments, others can comment on your reply again or reply, so repeated, theoretically can be said to be no repose, From the technical point of view it is easy to think of using infinite classification technology to store data, using recursive to get comment hierarchy data, using AJAX to implement Comment page interaction, here with thinkphp framework to do a simple demo practiced hand, in order to simplify the process here the third comment no longer provides a reply function, Of course, as long as on this basis a slight modification can achieve infinite reply function, mainly the view layer style modification is more troublesome, it takes some time.

First, the effect of demand analysis:

A first-level comment can be posted directly on the head, with the latest comments appearing on the top, as follows

Comments on the post can be replied to, the reply appears in the superior comments below, form a hierarchical relationship, as follows

Page operation Details: When you click the Reply button for a comment, the Reply text entry box appears, and the Reply text entry box for the other comment disappears, and the text box disappears when you click the Reply button again

In the last level comment (this is set to the third level) turn off the reply function

Show total comments in real time

Second, the realization of ideas and details

1. Data Sheet Design

2.controller Layer Key functions:

(1). Get a list of comments recursively

/***递归获取评论列表   */   protected function getCommlist($parent_id = 0,&$result = array()){           $arr = M('comment')->where(parent_id = '.$parent_id.')->order(create_time desc)->select();       if(empty($arr)){        return array();    }    foreach ($arr as $cm) {          $thisArr=&$result[];        $cm[children] = $this->getCommlist($cm[id],$thisArr);            $thisArr = $cm;                                        }    return $result;   }

(2). Action to display the comment page

public function index(){      $num =  M('comment')->count(); //获取评论总数    $this->assign('num',$num);      $data=array();    $data=$this->getCommlist();//获取评论列表    $this->assign(commlist,$data);      $this->display('index');  }

(3). Comment Page Ajax access the action to add a comment

/***添加评论   */   public function addComment(){                $data=array();    if((isset($_POST[comment]))&&(!empty($_POST[comment]))){        $cm = json_decode($_POST[comment],true);//通过第二个参数true,将json字符串转化为键值对数组        $cm['create_time']=date('Y-m-d H: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;    }    echo json_encode($data);   }

3.view Layer Implementation

(1). Overall structure design of the display page


Actual effect:

Page HTML code:

<title></title> {$num}条评论 发表评论 全部评论
    • {$data.nickname} {$data.create_time}

      {$data.content}

      回复 !--Level Two comments begin-->
        • {$child.nickname} {$child.create_time}

          {$child.content}

          回复
            • {$grandson.nickname} {$grandson.create_time}

              {$grandson.content}

(2). Single comment information div structure code

{$data.nickname} {$data.create_time}

{$data.content}

回复

Corresponds to:

The corresponding CSS code:

.head-pic{    width:40px;    height:40px;    }.cm{    position:relative;    top:0px;    left:40px;    top:-40px;    width:600px;}.cm-header{    padding-left:5px;}.cm-content{    padding-left:5px;}.cm-footer{    padding-bottom:15px;    text-align:right;    border-bottom: 1px dotted #CCC;}.comment-reply{    text-decoration:none;    color:gray;    font-size: 14px;}

4. JS Code

(1). Submit a comment: The A-tag button that submits the comment refers to the style comment-submit, and the Ajax action in its Click event

$ (' body '). Delegate ('. Comment-submit ', ' click ', function () {var content = $.trim ($ (this). Parent (). Prev (). Children (t Extarea). Val ());//Gets the current comment content $ (this) from the layout structure. Parent (). Prev (). Children (TEXTAREA). Val ();//Empty the input box if the content is finished (==content             {Alert (comment content cannot be empty!);            }else{var cmdata = new Object ();            cmdata.parent_id = $ (this). attr (parent_id);//Superior Comment id cmdata.content = content; Cmdata.nickname = tourist;//test Data Cmdata.head_pic =/public/images/default.jpg;//test Data var Replyswitch = $ (this). attr (Replyswitch);//Get reply Switch Lock properties $.ajax ({type:post, Url:/inde                              X.php/home/index/addcomment, data:{comment:JSON.stringify (Cmdata) }, Datatype:json, Success:function (data) {if (typeof (D Ata.error) ==undefined) {$ (. comment-reply). NexT (). Remove ()//delete all replies that already exist div//Update comments total $ (. Comment                        -num). Children (span). HTML (data.num+ reviews);                                             Show new comments var newli =; if (cmdata.parent_id = = 0) {//post is a first-class comment, add to the UL list in level NE  Wli =
  • +data.nickname++data.create_time+

    +data.content+

    回复
    • ; $(.comment-ul).prepend(newli); }else{ //否则添加到对应的孩子ul列表中 if('off'==replyswitch){//检验出回复关闭锁存在,即三级评论不再提供回复功能 newli =
      • +data.nickname++data.create_time+

        +data.content+

        • ; }else{//二级评论的回复按钮要添加回复关闭锁属性 newli =
          • +data.nickname++data.create_time+

            +data.content+

            回复
            • ; } $(li[comment_id='+data.parent_id+']).children(ul).prepend(newli); } }else{ //有错误信息 alert(data.error); } } }); } });

              (2). Reply to comments: The A-tag button of the reply comment refers to the style comment-reply, to show or hide the comment input box in its Click event

              //点击回复按钮显示或隐藏回复输入框    $(body).delegate(.comment-reply,click,function(){        if($(this).next().length>0){//判断出回复div已经存在,去除掉            $(this).next().remove();         }else{//添加回复div            $(.comment-reply).next().remove();//删除已存在的所有回复div                //添加当前回复div            var parent_id = $(this).attr(comment_id);//要回复的评论id            var divhtml = ;            if('off'==$(this).attr(replyswitch)){//二级评论回复后三级评论不再提供回复功能,将关闭属性附加到提交回复按钮                
              提交回复; }else{ divhtml = 提交回复; } $(this).after(divhtml); } });

        http://www.bkjia.com/PHPjc/1000537.html www.bkjia.com true http://www.bkjia.com/PHPjc/1000537.html techarticle PHP Infinite Classification of the actual combat-comment and reply function often in the major forums or the news section of the details page to see the comment function, of course, not only directly to comment content so simple, ...

      • Contact Us

        The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

        If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

        A Free Trial That Lets You Build Big!

        Start building with 50+ products and up to 12 months usage for Elastic Compute Service

        • Sales Support

          1 on 1 presale consultation

        • After-Sales Support

          24/7 Technical Support 6 Free Tickets per Quarter Faster Response

        • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.