jquery打字效果

时间:2011-12-30 02:31:40

标签: php jquery mysql html chat

我只是想知道你们可以推荐/建议我采取的方法。我正在尝试创建自己的简单实时支持聊天系统,并且需要为客户端创建一个功能,以便在代理键入消息时查看。我已经想出了如何为打字的人做这件事,但对于一个偏远的人却没有。

请帮忙,因为我不是很擅长jQuery!下面是我当前的代码,它只是在输入id为#chatMessage的输入字段时显示。请注意,这是一个PHP,MySQL和jQuery聊天系统。

$('#chatMessage').keyup(function(){
    if ($("#chatMessage").val() == ''){
        $('#typing').html('');
    }else{
        $('#typing').html('The agent is typing a message..');
    }
});

由于

1 个答案:

答案 0 :(得分:3)

您只需要向服务器添加ajax调用,然后在客户端上添加一个检查代理状态的计时器......

//代理方......

function checkStatus(){
      jQuery.get('/server-url?agent_id=32&status', function(data){
           if (data.status == 'typing')
               $('#typing').html('The user/client is typing a message..');
           else
               $('#typing').html('');
           checkStatus();
      });
}
// Start the function begining. 
setTimeout(checkStatus, 300);
var agent_timer;
$('#chatMessage').keyup(function(){ 
   if (agent_timer) 
        clearTimeout(agent_timer);

   if ($("#chatMessage").val() == ''){
      status = 'empty'; 
   } else { 
      status = 'writing';
   }
   agent_timer = setTimeout(function(){
       // Send status to server php script
       $.post('/server-url?agent_id=23', {status: status}, function(data){
           // handle response
       });
   }, 400);
});

//服务器端......

// check for agent, and other things...
if (isset($_GET['agent_id'])){
    // Agent server side
    if (isset($_POST['status']){
        // Save status to database
        $this->save(array('agent' => $agent, 'chat_id' => $chat_id, 'status' => $_POST['status']));
    }
    if (isset($_GET['status'])){
        $data = $this->read(array('agent_id' => $chat_id));
    }
} else {
    // This is the client server side
    if (isset($_GET['status'])) {
         $data = $this->read(array('chat_id' => $chat_id));
         return $data['status'];
    }
}
// handle other things and return data if necessary
// echo json_encode($data);

//客户端JS

function checkStatus(){
      jQuery.get('/server-url?chat_id=32&status', function(data){
           if (data.status == 'typing')
               $('#typing').html('The agent is typing a message..');
           else
               $('#typing').html('');
           checkStatus();
      });
}

// Start the function at begining.
setTimeout(checkStatus, 300);
// We can do the same, so the agent can know if user is typing too (you must also copy the above function)
var client_timer;
$('#chatMessage').keyup(function(){ 
   if (client_timer) clearTimeout(client_timer);
   if ($("#chatMessage").val() == ''){
      status = 'empty'; 
   } else { 
      status = 'writing';
   }
   client_timer = setTimeout(function(){
       // Send status to server php script
       $.post('/server-url?chat_id=23', {status: status}, function(data){
           // handle response
       });
   }, 400);
});

也许有更好的方法比更新mysql中的行...但我现在想不出来..