1

我正在为我的网站开发一个简单的网络聊天应用程序。但是,对我来说,使用间隔和每秒请求与 ajax 聊天感觉不对?

我今天要做的是

<script>

    $(function() {

        $('#chat_form').submit(function() {
            $.post('chat/post', $('#chat_form').serialize(), function(data){
                var message = $("#message").val();
                $("#message").val('');
                $("#chat_main").append('<li><b>Bruker: <?php echo " ".$this->session->userdata("chat_username") ?></b>: ' + message + '<br/></li>');
            });
            return false;
        });

        function loadchat()
        {
            $('#chat_main').load('chat/load');
        }

        setInterval(loadchat, 500);
        loadchat();

});

</script> 

还有其他更好的方法吗?

4

3 回答 3

1

您可以使用服务器端事件,它应该允许相同的事情,但在数据发生更改时将数据发送到浏览器,这样用户就不会不断请求查看是否进行了更改。

于 2012-12-07T12:03:21.743 回答
0

这是一篇关于聊天应用程序和使用 jQuery 实现彗星的最佳方法的非常酷的文章。

它对我有用。

为了使其完美,几乎不需要破解,因为它在时间戳中工作,因此当您更改机器日期时,它无法执行,但在服务器上它工作正常。

使用 xml 替换文本文件实现是一种很好的做法。

于 2012-12-07T12:34:37.167 回答
0

I wrote this couple of times. Ajax chat with polling from DB is not really a chat in real time. And you are right, using interval to poll data sucks. Anyway this is solution (one and only real solution).

You need to read this book. If you do not have jabber server I will give you acces to mine (user register update etc). Read the book and then contact me. It is XMPP + Strophe library chat (that what google and facebook are using)! So it is better to start over and learn something new!

于 2012-12-07T12:59:31.220 回答