刷新每个用户的聊天正文 [英] refreshing chat body for each of the users

查看:56
本文介绍了刷新每个用户的聊天正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用php + ajax + mysql创建一个聊天系统.

I have been trying to create a chatting system using php+ ajax + mysql.

 <?php
   session_start();
 ?>
 <html>  
     <head>  
         <title>Live Table Data Edit</title>  
         <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
         <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
         <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
     </head>  
     <body>  
         <div class="container">  
            <br />  
            <br />  
            <br />  
            <div class="table-responsive">  
                 <h3 align="center">You Are : <?php echo $_SESSION['name']; 
                ?></h3><br />  
                 <div id="live_data"></div>                 
            </div>  
            <div id="messages"></div> 
            <div class="area" style="display:none">
            <textarea id="text" name="text"></textarea>
            <input type="submit" id="sub" name="sub" value="Send" />
            </div>
       </div>  
  </body>  
</html>  

<script>  
$(document).ready(function() {
  function fetch_data() {
    $.ajax({
      url: "select.php",
      method: "POST",
      success: function(data) {
        $('#live_data').html(data);
      }
    });
  }
  fetch_data();

  $(document).on('click', '.first_name', function() {
    var id = $(this).data("id1");

    function fetch_chat() {
      $.ajax({
        url: "fetch_chat.php",
        method: "POST",
        data: {
          id: id
        },
        dataType: "text",
        success: function(data) {
          $('#messages').html(data);
          $("div.area").show();
        }

      });
    }

    function myTimeoutFunction() {
      fetch_chat();
    }

    myTimeoutFunction();
    setInterval(myTimeoutFunction, 1000);

    fetch_chat();
    $("#sub").click(function() {
      var text = $("#text").val();
      $.post('insert_chat.php', {
        id: id,
        msg: text
      }, function(data) {
        $("#messages").append(data);
        $("#text").val('');

      });
      alert(text);
    });
  });
});
</script>

但是此代码的问题在于,它仅适用于与我聊天的第一个用户,但是当我单击其他用户的名称时,屏幕开始频繁闪烁.例如:用户"a"已登录并单击用户"b"并开始聊天.到现在为止一切正常,但是当用户"a"认为要与另一个用户"c"聊天时,整个聊天部分开始闪烁,并且所有聊天记录都存储在数据库中.请告诉我我哪里错了.

but the problem with this code is that it worked only for the first user I chat with but the screen starting blinking frequently when I click on other users' name. for example: user 'a' is logged in and click on user 'b' and starts the chat. everything works fine till now, but when user 'a' thinks to chat with a another user 'c' the whole chat part start blinking with all chats stored in database. plz tell me where I m goin wrong.

推荐答案

这真的需要进行彻底的重新思考,以消除所有潜在的错误.

This needs a complete rethink really, to be rid of all the potential bugs.

您在上面描述的问题是因为每次有人单击名称时都在创建一个新的计时间隔,因此逐步建立起来,并且您每隔几毫秒而不是每秒请求一次.这是不可持续的.确实不需要在名称的"click"处理程序中声明间隔,函数等.我认为您正在执行此操作是因为选择名称会导致对用户ID的依赖性.但是,您可以通过将值分配给全局变量来克服这一问题.

The problem you describe above is because you're creating a new timed interval every time someone clicks on a name, so gradually this builds up and you are requesting every few milliseconds instead of every second. This is unsustainable. There's no need really to be declaring intervals, functions etc etc within the "click" handler of the name. I think you're doing this because of the dependency on the user ID which results from selecting a name. However you can overcome that by assigning the value to a global variable.

这样做意味着您可以将所有功能移到单击处理程序之外,从而消除了多次重新创建相同间隔/事件的任何危险.我也更改了它,所以它不使用间隔.取而代之的是,fetch_chat在收到上一个响应后2秒钟再次调用自身.这样,如果获取的时间比正常时间长,则不会有多个并行运行的竞争获取操作并引起潜在的混乱.我还增加了时间间隔,使之仍然合理,但不会使服务器超负荷.

Doing this means you can move all the functions outside the click handler, removing any danger of re-creating the same intervals / events multiple times. I've also changed it so it doesn't use an interval. Instead, fetch_chat calls itself again 2 seconds after the previous response is received. That way, if a fetch takes longer than normal, you don't have multiple competing fetch operations running in parallel and causing potential confusion. I also increased the time interval to something which is still reasonable, but won't overload the server.

这是您的代码的完整返工:

Here's a complete rework of your code:

<script>
var currentID = null;
var chatTimer = null;

function fetch_data() {
  $.ajax({
    url: "select.php",
    method: "POST",
    success: function(data) {
      $('#live_data').html(data);
      fetch_chat();
    }
  });
}

function fetch_chat() {
  $.ajax({
    url: "fetch_chat.php",
    method: "POST",
    data: {
      id: currentID
    },
    dataType: "text",
    success: function(data) {
      $('#messages').html(data);
      $("div.area").show();
      chatTimer = setTimeout(fetch_chat, 2000); //request the chat again in 2 seconds time
    }

  });
}

$(document).ready(function() {

  $(document).on('click', '.first_name', function() {
    currentID = $(this).data("id1");
    //immediately fetch chat for the new ID, and clear any waiting fetch timer that might be pending
    clearTimeout(chatTimer);
    fetch_chat(); 
  });

  $("#sub").click(function() {
    var text = $("#text").val();

    $.post('insert_chat.php', {
      id: currentID,
      msg: text
    }, function(data) {
      $("#messages").append(data);
      $("#text").val('');
    });
    alert(text);
  });

  fetch_data(); //this will also trigger the first fetch_chat once it completes
});
</script>

P.S.如果您希望刷新时间超过2秒,那么实际上您可能需要考虑使用websockets重新架构解决方案以获得完整的2向通信,因此服务器可以将聊天项目推送"给客户端,而不是客户端必须轮询服务器.

P.S. If you want anything faster than 2 seconds refresh, then really you probably need to consider re-architecting the solution using websockets to get full 2-way communication, so the server can "push" chat items to the client instead of the client having to poll the server.

这篇关于刷新每个用户的聊天正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆