PHP Unlimited Classification Combat--Comment and reply function

Source: Internet
Author: User
 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: * * 1. In the head can be directly published first-level comments, the latest comments on the top! [Write a description of the picture here]     ( 2. Comments on the post can be answered, the response is displayed in the upper level of comments below, forming a hierarchical relationship! [Write a description of the picture here]     ( 3. Page operation details: When clicking the Reply button of a comment, the reply text input box is displayed, and the Reply text input box of other comments disappears, and when you click the Reply button again, the text box disappears 4. In the last level comment (here is the third level) turn off the Reply function 5. Dynamic instant Display Total number of comments * * Ideas and Details: * * 1. Data Sheet Design! [Comment Form]     ( 2.controller Layer key function: ①. Recursive get comment list '/** * Recursive get comment list */protected function g Etcommlist ($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; } "' ②. The action ' Public Function Index () ' of the comment page is displayed {$num = M (' comment ')->count ();                Get Total Comments $this->assign (' num ', $num);                $data =array ();                $data = $this->getcommlist ();//Get a list of comments $this->assign ("Commlist", $data);            $this->display (' index ');            } "' ③. Comment Page Ajax Access add comment to action '/** * Add comment */                Public Function AddComment () {$data =array ();                   if ((Isset ($_post["comment")) && (!empty ($_post["comment"])) { $CM = Json_decode ($_post["comment"],true);//The JSON string is converted to a key-value array by the second parameter true $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 ();//The total number of statistical comments $data [' num ']= $num;                }else{$data ["error"] = "0";            } Echo Json_encode ($data); } ' 3.view layer implementation ①. Display the overall structure of the page design! [Write a description of the picture here] ( actual effect:! [Write a description of the picture here]                ( page HTML code:
     <title>PHP Infinite class Classification combat???? Comment and reply function</title>    
               {$num} article comments                        <textarea class="txt-commit" replyid="0"></textarea>                            Post a comment                      
             All reviews                    
  • {$data. Nickname} {$data. create_time}

    {$data. Content}

      • {$child. Nickname} {$child. create_time}

        {$child. Content}

        • {$grandson. Nickname} {$grandson. create_time}

          {$grandson. Content}

②. Single comment information div structure Code "'{$data. Nickname}                    {$data. create_time}                                                                

{$data. Content}

Reply ``` corresponding to:! [Write a description of the picture here] ( 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; } ' ③.js code: Use jquery to get event objects for event handling using a specified style
$ (function () {///Click Submit Comment Content $ (' body '). Delegate ('. Comment-submit ', ' click ', function () {var content = $.trim ($ (t His). Parent (). Prev (). Children ("textarea"). Val ()); Gets the current comment content from the layout structure $ (this). Parent (). Prev (). Children ("textarea"). Val ("");//Empty the input box if ("" ==content) {alert ("Comment cannot be empty!") after getting the content            else{var cmdata = new Object ();            cmdata.parent_id = $ (this). attr ("parent_id");//Superior Comment id cmdata.content = content;                          Cmdata.nickname = "Visitor";//test Data Cmdata.head_pic = "/public/images/default.jpg";//test data var Replyswitch = $ (this). attr ("Replyswitch");//Get Reply Switch Lock property $.ajax ({type: "POST", u                              RL: "/index.php/home/index/addcomment", data:{comment:JSON.stringify (Cmdata)                    }, DataType: "JSON", success:function (data) { if (typeof (data.error) = = "Undefined ") {$ (". Comment-reply "). Next (). Remove ()//delete all replies that already exist div//update comments Total                        Number of $ (". Comment-num"). Children ("span"). HTML (data.num+ "comment");                                             Show new comments var newli = "";                                               if (cmdata.parent_id = = "0") {//Post a first-level comment, add to the UL list Newli = "
  • "+data.nickname+" "+data.create_time+"


    • "; $ (". Comment-ul"). Prepend (Newli); }else{//Otherwise add to the corresponding child UL list if (' Off ' ==replyswit CH) {//Check out the reply-to-close lock exists, i.e. the three-level comment no longer provides a reply function Newli = "
    • "+data.nickname+" "+data.create_time+"


      • "; }else{//Two Comment reply button to add Reply close lock Property Newli = "
      • "+data.nickname+" "+data.create_time+"


        • "; } $ ("Li[comment_id= '" +data.parent_id+ "']"). Children ("ul"). Prepend (NE WLI); }}else{//Error message alert (DATA.ERROR); } } }); } }); Click the "Reply" button to show or hide the reply input box $ ("Body"). Delegate (". Comment-reply", "click", Function () {if ($ (this). Next (). length>0) {//judgment A reply div already exists to remove the $ (this). Next (). Remove (); }else{//Add reply div $ (". Comment-reply"). Next () remove ();//Delete all replies that already exist div//Add current reply div var p arent_id = $ (this). attr ("comment_id");//To reply to the comment id var divhtml = ""; if (' Off ' ==$ (this). attr ("Replyswitch") {///Level Two comment reply post three comments no longer provide a reply function, attach the close attribute to the "Submit Reply" button "divhtml ="<textarea class="txt-reply" replyid="2" style="width: 100%; height: 60px;"></textarea>Submit a Reply "; }else{divhtml = "<textarea class="txt-reply" replyid="2" style="width: 100%; height: 60px;"></textarea>Submit a Reply "; } $ (this). After (divhtml); } });})

          Third, complete code free download

        • 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: 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.