2017-05-21 8 views
0

私は現在、簡単なコメントセクションを作成しています。新しいデータがデータベースに挿入されると、テーブルがロードされます。ページ全体ではありません。私の質問は、javascriptと同じファイルにクエリを読み込むことによって、JavaScriptを使用してテーブルを更新する方法ですか?あなたはこれを達成するために、AJAXを使用する必要がjavascriptを使用してHTMLテーブルをリフレッシュ

comments.php

<?php 
    $getcomment = $conn->prepare("SELECT * FROM comments INNER JOIN document ON document.doc_groupid = comments.comment_doc INNER JOIN user ON user.user_matricno = comments.comment_user WHERE document.doc_id = :document ORDER BY comments.comment_timestamp DESC"); 
    $getcomment->bindParam(':document', $document, PDO::PARAM_STR); 
    $document = $_GET['doc']; 
    $getcomment->execute(); 
    readcomment = $getcomment->fetchAll(); 
    $countc = $getcomment->rowCount(); 

    foreach ($readcomment as $rc) { 
    echo 
    ' 
          <table class="table table-responsive nowrap table-hover"> 
          <tr> 
           <th style="border-top: #FFFFFF;pointer-events: none;">'. $rc["comment_subject"] .'</th> 
           <td class="pull-right" style="border-top: #FFFFFF;pointer-events: none;">by <strong>'. $rc["user_fname"].' '.$rc["user_lname"] .'</strong><small>&nbsp;'. time_elapsed_string($rc['comment_timestamp']).'</small></td> 
           </tr> 
          <tbody> 
           <tr> 
           <td colspan="2">'. $rc['comment_text'] .'</td> 
           </tr> 
          </tbody> 
          </table>'; 
    } 
?> 
<div id="tablecomment"></div> 

<script type="text/javascript"> 
    $(document).ready(function(){ 
     refreshTable(); 
    }); 

    function refreshTable(){ 
     $('#tablecomment').load('comments.php', function(){ 
      setTimeout(refreshTable, 5000); 
     }); 
    } 
</script> 

答えて

0

https://www.w3schools.com/xml/ajax_intro.asp

単一のコメントを記述することは少し複雑すぎる、と偉大なチュートリアルの多くはそこにあります。しかし、あなたがしたいと思っているのはあなたがすでにやっているものに似ています。タイムアウトを設定してajax(データベースデータを取得)を呼び出し、テーブルを更新します。

前のリクエストのデータが新しいものの後に到着する競合状態を避けるように注意してください。

関連する問題