2014-08-14 17:19
浏览 90


I am trying to build a live commenting system for my website (blog page homework). The idea is to use ajax to store comments in a mysql database and return JSON text for a comment without refreshing. I am 90% done with this I am just not sure how to format the JSON text to not look like crap.

The JSON returned for a comment is the following:

[{"c_name":"Test Commenter","c_date":"2014-08-14","comment":"This is a test comment"}]

On my comment page (postdetails.php) firstly I query the comments database table and return all the comments already stored for a particular post. The user then can enter a comment form > submit it > and the JSON text returned from the ajax function will appear on the page automatically.

The initial comments already stored in the table are displayed via a php function:

// Display comments in nice format 
          while ($row2 = mysql_fetch_array($result2))
              echo "<div class = 'comments_user'>
                  echo "<p>" . $row2['c_name'] ."</p>
              echo "</div>
              echo "<p class = 'date'>" . $row2['c_date'] . "</p>"; 
              echo "<p>" . $row2['comment'] ."</p>

My issue is getting the JSON text to display in a similar format underneath the previous comments. I have plain old HTML to display the JSON returned comments. Which I should be able to manipulate with the DOM by targeting the p tag id's shown below :

    <!--Use JS and the DOM to manipulate this (live commenting)-->
        <div class = "comments_user">
            <p id = "commenter"></p>
        <div class = "date_wrap">
            <p id = "c_date"></p>
            <p id = "comment_content"></p>

The JSON text is returned in the 'result' variable. This is passed to my JSON_to_HTML function:

function JSON_to_HTML(result){
    var CM = JSON.parse(result);        

   // Need to traverse the DOM and display the array contents (JSON)

My question is how can I add these comments using the DOM to the plain HTML code shown above? I know i can get the p-tag values using document.getElementById("c_date"); and so forth but how can I append children onto these? I am familiar with the Jquery append method but for this I can ONLY use vanilla Javascript.

One thing I tried was to have a global variable to track how many times the ajax function was called (number of comments per session). For each comment I could traverse the DOM and append a child to the commenter, date and comment page. However I was not able to get this quite working.

My last resort would be to return the JSON into a simple table (which I know how to do).

Any ideas here? Thanks!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douyi5961 2014-08-14 17:30

    If you already have the html structure in place, you can do:

    document.getElementById("c_date").textContent = CM[0].c_date;
    // etc.

    And if you want to add html instead of plain text, you can use innerHTML instead.

    点赞 评论

相关推荐 更多相似问题