聊天ajax加载消息在彼此之上

时间:2016-10-21 16:01:32

标签: javascript php jquery ajax

我的代码存在问题,群聊的消息正在相互加载。而不是仅加载新的和每秒检查。 这是我拉动chat-load-group.php文件的代码

<div class="Rooms">
  <div class="row">
    <div class="col-xs-12">
      <div id="messages" class="messages message-window" id="style-1" room_id="$id">
                    <ul  id="ScrollAuto" class="message">
       <!--  <span class="recieved">Casper <h5>Message 1</h5></span><br/>
        <span class="sent"><h5>Message 2</h5></span><br/> -->
        </ul>
        </div>
      </div>
    </div>
  </div>
  <form id="SendForm" role="form" method="post" autocomplete="off" />
    <div class="row SendMessage">
      <div class="col-xs-10">
        <input style="display:none" name="id" value="<?=$_SESSION['user']['username']?>"/>
        <input style="display:none" name="room_id" value="<?=$id?>"/>
        <textarea name="message" id="message" placeholder="Have your say"></textarea>
      </div>
      <div class="col-xs-2">
        <button>Send</button>
      </div>
    </div>
  </form>
</div>




<?php endwhile;?>
              <script>
  $(function() {
    $(document).on('submit', 'form#SendForm', function(e){
    e.preventDefault();
          $.post('elements/sendmessagegroup.php', $(this).serialize(), function (data) {
              // This is executed when the call to mail.php was succesful.
              // 'data' contains the response from the request
              $('#message').val(''); 
          })
          .error(function() {
              $('#message').val('');        
               });
          e.preventDefault();
                      $('#message').val(''); 
    })

  });

  $(document).ready(function(){
    
      $('div.message-window').each(function(index, messageWindow) {
      messageWindow = $(messageWindow);         
      // Run fetchMessages() once, when the page is loaded.
      fetchMessages(messageWindow);               
      // Set an interval timer for checking messages.
      // Not ideal, but it works for now.
      setInterval(fetchMessages, 1000, messageWindow);
      // in milliseconds!!!!!! (1000ms = 1s)
    });
    });         
  function fetchMessages(messageWindow) {
        // For each message window, check for new chats
        // Get the friend_id from the window
        var room_id = <?=$id?>;           
        // Get the last chat message_id from the last chat message in this window.
        var last_message_id = messageWindow.find("ul > li:last").attr("message_id");                
        // Ask the server for the latest messages.
        // Send over the friend_id and last_message_id, so it can send back new messages from this friend.
        $.get("elements/chat-load-group.php", {
        last_message_id: last_message_id,
        room_id: room_id
        }, function(messages) {
        // This function is run when the AJAX request succeeds.               
        // Append the new messages to the end of the chat
          messageWindow.find("ul").append(messages);
          });
    }
</script>

这是chat-load-group.php文件

<?php


	
	session_start();
	if(!isset($_SESSION["user"]) or !is_array($_SESSION["user"]) or empty($_SESSION["user"])) {
		// redirect to index page if not superuser
		header('Location: index');
	}
		$room_id = filter_var((int)$_GET['room_id'], FILTER_VALIDATE_INT);


	$last_message_id = filter_var((int)$_GET['last_message_id'], FILTER_VALIDATE_INT);
	
	// If validation fails, default 'last message ID' to zero.
	// This way, if we don't provide the last message ID, we will get all the messages.
	if($last_message_id === false or empty($last_message_id)) $last_message_id = 0;
$con = mysqli_connect('**','**','**','**');
	if (!$con) die('Could not connect: ' . mysqli_error($con));
	
	/*
	$sql="SELECT IF(friends.sender = ".$_SESSION["user"]["id"].", friends.recipient, friends.sender) AS user_id
	FROM friends
	WHERE friends.sender = ".$_SESSION["user"]["id"]."
		OR friends.recipient = ".$_SESSION["user"]["id"]."";
		$Frind = mysqli_query($con,$sql);
	while($Friends = mysqli_fetch_array($Frind)) {
	$sql="SELECT firstname, lastname, id FROM users WHERE id = ".$Friends['user_id']." ";
		$UsrFrind = mysqli_query($con,$sql);
	while($UserFriends = mysqli_fetch_array($UsrFrind)) {
	*/
	// Query for messages to/from $friend_id, with a message.id higher than $last_message_id.
	$sql="SELECT * FROM group_messages WHERE room_id = $room_id AND id > $last_message_id";
	$messages = mysqli_query($con, $sql);
	
	while($message = mysqli_fetch_array($messages)) {

		echo "<span class='recieved' message_id='". $message['id'] ."'>";
		echo $message['id']."<h5>".$message['message']."</h5>";
		echo "</span>";
	};
?>

1 个答案:

答案 0 :(得分:0)

如果您不想继续加载相同的邮件块,则应保持已加载的邮件总数的运行总计。然后,您可以在服务器端检索消息时将其用作偏移量。