Ajax / jQuery评论系统

Building a comment system with Ajax and JQuery and I want the div the comments are in to reload after a comment is added. It posts just fine. This is what I have so far.

The function getComments queries the database and generates the html

$.ajax({
type: "POST",
url: "post_comment.php",
data: dataString,
cache: false,
success: function(html){

????????? What should go here... it is a div with id#commentBody

}

<div id="commentBody">
    <ul>
    <?php
        $q = "SELECT * FROM comment WHERE parent_id = 0 AND idpost = $postID";
        $r = mysql_query($q);
        while($row = mysql_fetch_assoc($r)):
            getComments($row,$postID,$custID);
        endwhile;
    ?>
    </ul>
</div> 

Since you're regenerating the entire div I would use replaceWith.

$('#commentBody').replaceWith(html);

When you post it, you should return the data you want from your server side script. Then you can use the .html() jQuery function to update your div.

So, like:

$('#commentBody').html(html);

You could also return just the latest comment (optionally as a JSON object) and then just use the .append() method to add it to your #commentBody.

I would create a JSON object which has a status property and a data property. When the status is -1 (or whatever) there was an error adding the comment and you could put a message in the data property. When the status is 0, it was successful and the latest comment information would be available available in the data property.

Example

PHP

//Check postback variables, add comment and retrieve
//  comment information (such as ID) if necessary
if (postedsuccessfully) {
   $ary = array("status" => 0,
                "data" => array("id" => $commentidvar,
                                "user" => $commentuser,
                                "text" => $comment)
               );
   echo json_encode($ary);
} else {
   $ary = array("status" => -1,
                "data" => "There was a problem adding your comment.");
   echo json_encode($ary);
}

JavaScript

success: function(json){
   if (json.status == 0) {
      $mydiv = $('<div>');//construct your comment div using json.data.id,
                          //json.data.user, and json.data.text
      $('#commentBody').append($mydiv);
   } else {
      alert(json.data);
   }
}