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

时间:2016-06-25 15:49:14

标签: javascript ajax

我有这段代码可以检测用户是否根据this answer进行输入。我想通过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代码的位置是否正确。谁能解释我哪里出错?

2 个答案:

答案 0 :(得分:1)

请再次检查:

$(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/

答案 1 :(得分:1)

将你的ajax代码放在keypress事件上。
在您的情况下,您应该在 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>