如何实现“用户输入”功能并发送到服务器

How to implement "user is typing" functionality and send to server

本文关键字:功能 用户输入 并发 服务器 输入 用户 何实现 实现      更新时间:2023-09-26

我有这段代码来检测用户是否在根据这个答案打字。我想通过ajax发送响应到服务器,通过放置我的ajax代码在某个地方的if/else语句,但我不确定如何。

var textarea = $('#textarea');
var typingStatus = $('#typing_on');
var lastTypedTime = new Date(0); // it's 01/01/1970, actually some time in the past
var typingDelayMillis = 5000; // how long user can "think about his spelling" before we show "No one is typing -blank space." message
function refreshTypingStatus() {
  if (!textarea.is(':focus') ||
      textarea.val() == '' ||
      new Date().getTime() - lastTypedTime.getTime() > typingDelayMillis) {
    typingStatus.html('No one is typing -blank space.');
  } else {
    typingStatus.html('User is typing...');
  }
}
function updateLastTypedTime() {
  lastTypedTime = new Date();
}
setInterval(refreshTypingStatus, 100);
textarea.keypress(updateLastTypedTime);
textarea.blur(refreshTypingStatus);

我已经试过了:

var textarea = $('#chatbox');
var typingStatus = $('#typing_on');
var lastTypedTime = new Date(0); // it's 01/01/1970, actually some time in the past
var typingDelayMillis = 5000; // how long user can "think about his spelling" before we show "No one is typing -blank space." message
function refreshTypingStatus() {
  if (!textarea.is(':focus') ||
      textarea.val() == '' ||
      new Date().getTime() - lastTypedTime.getTime() > typingDelayMillis) {
    typingStatus.html('No one is typing -blank space.');
  } else {
    typingStatus.html('User is typing...');
    $.ajax({
      type: "POST",
      url: "usertypes.php?v=<?php echo $usarr; ?>",
    });
  }
}
function updateLastTypedTime() {
  lastTypedTime = new Date();
}
setInterval(refreshTypingStatus, 100);
textarea.keypress(updateLastTypedTime);
textarea.blur(refreshTypingStatus);

然而,我的似乎没有发送任何回复。所以我不确定ajax代码的位置是否正确。谁能解释一下我哪里出错了?

请重新检查:

$(document).ready(function() {
    console.log("ready!");
    var typing = false;
    var timeout = undefined;
    var typingDelayMillis = 1000;
    function timeoutFunction() {
        typing = false;
        $.ajax({
            type: "POST",
            url: "usertypes.php?v=<?php echo $usarr; ?>&isTyping="+typing,
        });
        $('#typing_on').html("");
    }
    var delay = (function() {
        var timer = 0;
        return function(callback, ms) {
            clearTimeout(timer);
            timer = setTimeout(callback, ms);
        };
    })();
    $('#chatbox').keypress(function(e) {
        if (typing === false && $("#chatbox").is(":focus")) {
            delay(function() {
                timeoutFunction();
            }, typingDelayMillis);
            typing = true;
            $.ajax({
              type: "POST",
              url: "usertypes.php?v=<?php echo $usarr; ?>&isTyping="+typing,
            });
            $('#typing_on').html("user types...");
        }
    });
    $('#chatbox').on("blur", function() {
        clearTimeout(timeout);
        timeout = setTimeout(timeoutFunction, typingDelayMillis);
    })
});

在线演示:https://jsfiddle.net/vo46gehw/5/

将ajax代码放在按键事件上。
在你的情况下,你应该在updateLastTypedTime函数中使用ajax代码,而不是在setInterval的回调中编写它,该回调在1秒内执行10次。

<script>
    var textarea = $('#chatbox');
    var typingStatus = $('#typing_on');
    var lastTypedTime = new Date(0); // it's 01/01/1970, actually some time in the past
    var typingDelayMillis = 5000; // how long user can "think about his spelling" before we show "No one is typing -blank space." message
    function refreshTypingStatus() {
      if (!textarea.is(':focus') ||
          textarea.val() == '' ||
          new Date().getTime() - lastTypedTime.getTime() > typingDelayMillis) {
        typingStatus.html('No one is typing -blank space.');
      } else {
        typingStatus.html('User is typing...');

      }
    }
    function updateLastTypedTime() {
      lastTypedTime = new Date();
      $.ajax({
          type: "POST",
          data: {var: 'value'},
          url: "usertypes.php",
          dataType: 'json',
          success: function(response) {
            console.log(response);
          },
          error: function(jqXHR, textStatus, errorThrown) {
              // if error , code here.. 
          }
        });
    }
    setInterval(refreshTypingStatus, 100);
    textarea.keypress(updateLastTypedTime);
    textarea.blur(refreshTypingStatus);
</script>