我正在私聊系统。我使用php和javascript和很多帧。:d

frames:

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

| chat messages here        |                         

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

|send message frame         |

-------------*---------------
.

我想更新聊天消息的框架,但我想做它很酷的方式。你知道我是否只是重新加载看起来酷的框架。如果我只是重新加载一个小士,那可能有点更好,但我不知道......我的意思是:

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

你知道我的意思,没有?......我很抱歉我的英语穷人......如果你明白我,你能帮我一个吗?

有帮助吗?

解决方案

如果您的意思是如何向下滚动到视图的底部,请使用scrollTop。我在这里有一个例子来看看我的意思 - http://jsfiddle.net/uplwt/

其他提示

您可以通过jquery ajax post执行此操作。检查一下(http://api.jquery.com/jquery.post/)有一个榜样来更新div。

此处将此非常简单的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
?>
.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top