2016-08-16 74 views
1

如何显示来自ajax的输出并避免使用php echo显示数据以防止在刷新页面或单击回复或删除链接时重复相同的结果?如何使用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; 

action.php的

<?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

<?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标记。 您的包括整个index.php输出再次在您的show_messages()方法,包括JavaScript和<body>(这可能是重复条目的原因)!编写一个单独的文件,它只是返回HTML中的注释并在AJAX调用中使用它。

+0

感谢您的建议,如果我创建另一个文件来显示评论,它工作正常。但是,我的问题是当我试图创建一个包含ajax和php代码的php文件时,它可以简化我的工作,当我想将comment.php文件包含在不同的页面中时,它可以显示页面的注释。我怎样才能做到这一点? – enance

+0

就像你用'db_connect.php'所做的那样:将冗余代码重构成它自己的文件和include文件,甚至是require文件(如果文件丢失,require会失败,而include只会提示)。代码将被执行,就好像它在该确切点上被复制粘贴一样。你可能也想看看Symfony或者Zend等框架,因为从1999年开始,一切从零开始。 – YetiCGN

+0

你好,我又回来了。我想使用JSON编码显示“index.php”,我该如何显示带有JSON变量和aJax的数据? – enance