javascript - 用户正在输入通知

标签 javascript jquery asp.net-mvc asp.net-mvc-4

我在 mvc4 上开发我的项目,我有一个问题,用户在我的项目的聊天模块上输入状态通知。这个 j 脚本的问题是它向正在输入的同一用户显示状态,但我希望其他用户看到我正在我的文本框中输入

      var textarea = $('#textarea');
var typingStatus = $('#typing_on');
var lastTypedTime = new Date(0); // it's 01/01/1970
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);

<label>
<textarea name="textarea" id="textarea" cols="45" rows="5"></textarea>
</label>
<div id="typing_on"></div>

最佳答案

如果您希望用户看到不同的用户输入状态,您必须通过 AJAX 将当前用户状态发送到服务器并从服务器检索它以显示。

所以基本上,假设两个人在聊天,每个客户端(浏览器)必须:

  • 获取当前用户的打字状态并发送到服务器
  • 从服务器获取其他用户的输入状态并显示。

如果您不确定如何使用 AJAX,您应该查找 jQuery 的 ajax documentation

您的客户端代码必须像这样更改:

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 call to send typingStatus.html to server
  //AJAX call to retrieve other users typingStatus (could be combined into one call)
}

编写必要的代码超出了 SO 答案的范围,因为它涉及服务器端和客户端代码,但是 start with this tutorial ,如果您有更多问题,只需提出一个特定于您需要的新问题即可。

关于javascript - 用户正在输入通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18706521/

相关文章:

Javascript 排序项目排除某些特定项目

javascript - 语法错误: Invalid destructuring assignment target or ReferenceError: invalid assignment left-hand side?

javascript - 构建 Web 组件时如何修复 "You are running Vue in development mode"?

javascript - 用 Angular 干燥 HTML

c# - 操作使用变量值作为参数名称

asp.net-mvc - 无法访问文件

asp.net-mvc - 为什么将此路由参数添加到查询字符串中?

javascript - 如何使用 jQuery 函数启动图像淡出和淡入

javascript - 点击div动态创建

javascript - 突出显示单个单元格