如何使用ajax显示数据

时间:2016-08-16 09:59:29

标签: php

如何显示ajax的输出并避免使用php echo显示数据以防止在页面刷新或点击回复或删除链接时重复相同的结果?

这是我的代码

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 个答案:

没有答案