2016-08-16 8 views
1

どうすればajaxの出力を表示し、ページを更新したとき、または返信または削除リンクをクリックしたときに同じ結果が重複しないように、ここajaxを使用してデータを表示する方法

は私のコード

table_comments.sqlある

CREATE TABLE IF NOT EXISTS `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT, 
`idparent` int(5) unsigned NOT NULL DEFAULT "0", 
`user` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, 
`text` text CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, 
`date` datetime DEFAULT NULL, 
PRIMARY KEY (`id`) 
) 
ENGINE=MyISAM 
DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci 
AUTO_INCREMENT=1; 

<?php 
include ("db_connect.php"); 

// Get the variables from forms 
$user = $_REQUEST['user']; 
$text = $_REQUEST['text']; 
$comment_on = $_REQUEST['comment_on']; 
$ParentId = $_REQUEST['ParentId']; 
$action = $_REQUEST['action']; 

if ($action == "add") { 
    // Add data to the database  
    $query = "INSERT into `comments` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW(),'{$comment_on}')"; 
    $result = mysql_query($query); 
} 

if ($action == "delete") { 
    // Delete data from the database  
    $result = mysql_query("DELETE FROM `comments` WHERE id=$text"); 
} 
?> 

のindex.php

action.php 210
<?php header('Content-type: text/html; charset=utf-8') ?> 
<html> 
    <head> 
     <script type="text/javascript" src="jquery-1.11.2.min.js"></script> 
    </head> 
    <body> 

    <div id="table_content" >//Display result using ajax</div> 

    <script>  
     function show_messages() 
     { 
     $.ajax({ 
      url: "index.php", 
      cache: false, 
      success: function(html){ 
      $("#table_content").html(html); 
      } 
     }); 
     } 

     function clean_form() 
     { 
     $("#user").val('name'); 
     $("#text").val('comment'); 
     } 

     $(document).ready(function(){ 
     // show_messages(); 

     }); 
    </script> 

    <script> 
    function DeleteComment(number) // Function to remove comments with id = number 
    { 
     $.ajax({ 
     type: "POST", 
     url: "action.php",     
     data: "user=1"+"&text="+number+"&ParentId=1"+"&action=delete",     
     success: function(html){       
      // show_messages();    
      } 
     }); 
    } 

    function AnswerComment (id) // Send the comment numbers , which correspond to 
    { 
     $.ajax({ 
     type: "POST", 
     url: "index.php",     
     data: "AnswerId="+id,     
     success: function(html){       
      $("#table_content").html(html);    
      } 
     });  
    } 

    function SendComment() // Send data from the form 
    { 
     var user1 = $("#user").val(); 
     var text1 = $("#text").val();  
     var ParentId1 = $("#ParentId").val() + ""; 
     if (user1 =='' || user1 =='name') 
     { 
     alert ("Enter your Username"); 
     return false; 
     } 
     if (text1 =='' || text1 =='comment') 
     { 
     alert ("Enter name to comment"); 
     return false; 
     } 

     $.ajax({ 
     type: "POST", 
     url: "action.php",     
     data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",   
     success: function(html){     
      // show_messages(); 
      // clean_form();  
      } 
     }); 
     return false; 
     } 
    </script> 

    <?php 
    function ShowForm($AnswerCommentId) // Form add a comment 
    { 
     ?> <br/> 
     <form id="myForm" action=""> 
     <input id="user" name="user" value="name" autocomplete="off" 
     onfocus="if(this.value == 'name'){this.value = ''}" 
     onblur="if(this.value == ''){this.value = 'name'}"/>     
     <br/><br/> 
     <textarea id='text' name='text' value="comment" 
      onfocus="if(this.value == 'comment'){this.value = ''}" 
      onblur="if(this.value == ''){this.value = 'comment'}" ></Textarea>   
     <input id="ParentId" name="ParentId" type="hidden" value="<?php echo($AnswerCommentId);?>"/> 
     <br/> 
     <button type='button' OnClick=SendComment()>Comment</button> 
     </form> 
     <br/> 
     <?php 
    } 

    include ("db_connect.php"); // Connect to the database 

    $query="SELECT * FROM `comments` ORDER BY id ASC"; 
    $result = mysql_query($query); 

    // Read the comment number to which the answer , if it exists 
    if (isset($_REQUEST['AnswerId'])) 
    { 
     $AnswerId = $_REQUEST['AnswerId'];  
    } 
    else 
    { 
     $AnswerId = 0; 
    } 

    // Read comments from the database and writing the array     
    $i=0; 
    while ($mytablerow = mysql_fetch_row($result)) 
    { 
     $mytable[$i] = $mytablerow; 
     $i++; 
    } 

    // Function for constructing a tree Comments 
    function tree($treeArray, $level, $pid = 0) { 
     global $AnswerId; 
     if (!$treeArray) { 
     return; 
     } 
     foreach ($treeArray as $item) { 
     if ($item[1] == $pid) { 
      ?>  
       <!-- Showing each comment with the correct indentation --> 
       <div class="CommentWithReplyDiv" style="margin-left:<?php echo($level * 60); ?>px">  
       <div class="CommentDiv"> 
       <pre class="Message"><?php echo($item[3]); ?></pre> 
       <div class="User"><?php echo($item[2]); ?></div> 
       <div class="Date"><?php echo($item[4]); ?></div> 
      <?php 
      if ($level <= 4) { // Limit nesting level 
      echo '<a href="" class="ReplyLink" onclick="AnswerComment(' . $item[0] . ');return false;">Reply</a>'; 
      } 
      echo '<a href="" class="DeleteLink" onclick="DeleteComment(' . $item[0] . ');return false;">Delete</a>'; 
      ?> </div> <?php 
      // Display the form for an answer, if the answer Comment 
      if ($AnswerId == $item[0]) { 
      ?><div id="InnerDiv"><?php 
      ShowForm($AnswerId); 
      ?></div><?php 
      } 
      ?> </div> <?php 
      echo ('<br/>'); 
      tree($treeArray, $level + 1, $item[0]); // Recursion 
     } 
     } 
    } 

    tree($mytable, 0); 
    ?> 

    <!-- Reply form at the bottom of the page--> 
    <br/> 
    <a href="" id="LeaveCommentLink">leave a comment</a> 
    <div id="MainAnswerForm" style="display:none;"> 
     <?php 
     ShowForm(0); 
     ?> 
    </div> 
    <div id="AfterMainAnswerForm"></div> 

    <script> 
    // The emergence reply form at the bottom of the page when you click on the link 
    $(document).ready(function(){ 
     $("#LeaveCommentLink").click(function() { 
     $("#InnerDiv").remove(); 
     $("#MainAnswerForm").slideToggle("normal"); 
     return false; 
     }); 
    }); 
    </script> 

    </body> 
</html> 

答えて

0

JavaScriptコードとHTMLマークアップだけでなく、データベースアクセス、ビジネスロジック、ビューレイヤーを分離してください。 JavaScriptと<body>(恐らく重複したエントリの原因になります)を含めて、show_messages()メソッドにもう一度index.phpという出力を含めます。 HTMLのコメントを返すだけの別ファイルを作成し、AJAX呼び出しでそのコメントを使用します。

+0

ご意見ありがとうございます。コメントを表示するために別のファイルを作成しても問題ありません。しかし、私の問題は、私が別のページにcomment.phpファイルを含める場合、私の仕事を単純化することができるので、ページのコメントを表示できるように、ajaxとphpコードを含む1つのPHPファイルを作成しようとしているときです。どうやってやるの? – enance

+0

'db_connect.php'と同じように:冗長コードを独自のファイルにリファクタリングし、' include'または 'require'することもできます(インクルードは警告のみですが、ファイルが見つからない場合は失敗します)。コードは、その正確な位置にコピーペーストされたかのように実行されます。 symfonyやZendのようなフレームワークも見てみたいと思うかもしれません。なぜなら、ゼロから全てをやり直すのは1999年以来のスタイルではないからです。 – YetiCGN

+0

こんにちは、もう一度戻ってきました。 JSONエンコードを使用して "index.php"を表示したいのですが、JSON変数とaJaxでデータを表示するにはどうしたらいいですか? – enance