2012-09-29 2 views
-1

저는 개인 채팅 시스템에서 일하고 있습니다. 나는 PHP와 Javascript와 많은 프레임을 사용한다. : D아약스 채팅에서 새 메시지로 스크롤하는 방법은 무엇입니까?

frames: 

-------------*--------------- 

| chat messages here  |       

-------------*--------------- 

|send message frame   | 

-------------*--------------- 

채팅 메시지가있는 프레임을 업데이트하고 싶지만 멋진 방법으로하고 싶습니다. 나는 시원하게 보이지 않는 프레임을 다시로드하는지 알 수 있습니다. 난 그냥 작은 사업부를 다시로드하면, 어쩌면 조금 더 나은,하지만 나도 몰라 ...이 의미 :

function newMessageShow() 
{ 
print messages ... 
// wait 10-20 sec... somehow 
newMessageShow(); 
} 

당신은 내가 무슨 뜻인지, 아니? ... 가난한 영어에 대해 유감 이군 ... 나를 이해하면 나 좀 도와 줄 수 있니?

+3

. 당신이 시도한 것을 보여주십시오. –

답변

1

아래쪽으로 스크롤하는 방법을 의미하는 경우 scrollTop을 사용하십시오. 여기에 예제가 있습니다. - http://jsfiddle.net/uPLWT/

+0

그래, 나는 새 메시지를 보여주고 그 (것)들까지 아래로 스크롤 것을 의미했다. 그러나 당신은 내가 최신 메시지로 새로운 div를 표시하는 페이지를 리프레시하지 않는다는 것을 알고있다. 그리고 나는 가장 최근의 div로 스크롤해야한다. –

0

jQuery ajax 게시물을 통해이 작업을 수행 할 수 있습니다. 이것을 확인하십시오 (http://api.jquery.com/jQuery.post/) div를 업데이트하는 예제가 있습니다.

+0

보내기 버튼을 클릭 할 때만 업데이트되는 것 같습니다. 내 옆에서 모든 이벤트를 withouth로 업로드하고 싶습니다. –

+0

@ user1709024 그런 다음 'setInterval' (https://developer.mozilla.org/en-US/docs/DOM/window.setInterval)과 같은 것을 사용하여 모든 것을 실행합니다. 자주 새 메시지가 있는지 확인하십시오. – Ian

0

매우 간단한 AJAX 채팅 예제를 사용하여 서버를 폴링하고 최신 25 개의 메시지를 받고, $ ajax.post()를 사용하여 메시지를 보냅니다. 메시지는 단순화를 위해 sqlite에 저장됩니다. 아마도 관심이있을 것입니다.

채팅 페이지 : 정지 프레임을 사용하고 아약스와 새 메시지 서버를 폴링

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Simple AJAX Chat</title> 
<script src="http://code.jquery.com/jquery-latest.js"></script> 
<script> 
function get_chat(){ 
    var oldscrollHeight = $("#chat_log")[0].scrollHeight; 

    $.ajax({ url: "./chat.php", cache: false, 
    success: function(data){ 
     if(data.chat==null){ 
     }else{ 
      $("#chat_log").html(data.chat); 

      //Scroll to bottom of chat log on new message 
      var newscrollHeight = $("#chat_log")[0].scrollHeight; 
      if(newscrollHeight > oldscrollHeight){ 
       $("#chat_log").scrollTop($("#chat_log")[0].scrollHeight); 
      } 
     } 
     poll(); 
    }, dataType: "json"}); 
} 

function poll(){ 
    setTimeout(function(){ 
     get_chat(); 
    }, 1500); 
} 

$(document).ready(function(){ 
    //Send message 
    $("button").click(function() { 
     var text = $("#chat").val() 
     $.post("chat.php", { chat: text }); 
    }); 
    poll(); 
}); 
</script> 
<style> 
#chat_log{ 
    border:solid 2px #ddd; 
    background:#ccc; 
    color:#000; 
    padding:4px; 
    width:500px; 
    height:150px; 
    overflow:auto; 
} 
</style> 

</head> 

<body> 

<h1>AJAX Chat Polling Example</h1> 
<p>Chat Log:</p> 
<div id="chat_log">Loading chat...</div> 
<p>Send Message:</p> 
<div id="chat_send"> 
    <p><input id="chat" type="text" name="chat" size="42"><button>Send</button></p> 
</div> 

</body> 
</html> 

채팅 리시버/컨트롤러와 모델 (chat.php)

<?php 
// A simple table for chat messages 
$chat_table = array("CREATE TABLE chat (id INTEGER PRIMARY KEY, 
              user TEXT, 
              message TEXT);"); 
// Create a chat store instance. 
$chat_store = new chat_store("sqlite:./chat.db", $chat_table); 

// User posted to chat 
if(isset($_POST['chat'])){ 
    $chat_store->insert(array(array('user'=>$_SERVER['REMOTE_ADDR'],'message'=>$_POST['chat']))); 
}else{ 
    // Grab latest 25 messages 
    $result = $chat_store->get_chat_messages(25); 
    // Send as json so jquery can use it to insert into #chat_log 
    header('Content-Type: application/json'); 
    // Build an output 
    $chat = null; 
    foreach($result as $row){ 
     $chat .= '<p>'.$row['user'].' : '.$row['message'].'</p>'; 
    } 
    //Send the json string 
    echo json_encode(array('chat'=>$chat)); 
    die; 
} 
//End Logic 

/** 
* Chat store class, using sqlite & PDO to store and get your chat messages. 
*/ 
class chat_store{ 
    private $db; 

    function __construct($dsn,$setup_query){ 
     $this->dsn = $dsn; 
     $this->setup = $setup_query; 
     $this->chkSetup(); 
    } 
    /** 
    * Connect 
    */ 
    public function connect(){ 
     try{ 
      if (!$this->db instanceof PDO){ 
       $this->db = new \PDO($this->dsn); 
       $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
       $this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 
       $this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC); 
      } 
     }catch (Exception $e){ 
      die($e->getMessage()); 
     } 
    } 
    /** 
    * Get chat messages 
    * 
    * @param int $count 
    * @return array 
    */ 
    public function get_chat_messages($count){ 
     $this->connect(); 
     $sql = "SELECT * FROM chat LIMIT ".$count; 

     $statement = $this->db->prepare($sql); 
     $statement->execute(); 
     return $statement->fetchAll(PDO::FETCH_ASSOC); 
    } 

    /** 
    * Insert message into store 
    * 
    * @param array $values 
    */ 
    public function insert($values){ 
     $this->connect(); 
     $fieldnames = array_keys($values[0]); 
     $fields = '('.implode(' ,',$fieldnames).')'; 
     $bounds = '(:'.implode(', :',$fieldnames).')'; 
     $sql = "INSERT INTO chat {$fields} VALUES {$bounds}"; 
     $statement = $this->db->prepare($sql); 
     foreach($values as $vals){ 
      $statement->execute($vals); 
     } 
    } 

    /** 
    * Setup and Create table for store 
    */ 
    function chkSetup(){ 
     $dso = explode(':',$this->dsn); 
     if(file_exists($dso[1])){ 
      return; 
     }else{ 
      $this->connect(); 
      //Setup Table 
      if(is_array($this->setup)){ 
       foreach($this->setup as $table){ 
        $this->db->query($table); 
       } 
      }else{ 
       $this->db->query($this->setup); 
      } 
      exit(header("refresh:0;url=./")); 
     } 
    } 
}//End Class 
?> 
+0

badoo.com를 아십니까? 그런 채팅을하고 싶습니다 ... jquery 스크립트를 사용합니다. 내 문제는 실시간으로 메시지를 표시하는 것뿐입니다 ... 새 메시지를 가져오고 새 메시지를 새로 고침하는 페이지로 스크롤 ... –

관련 문제