阿贾克斯长轮询 [英] Ajax Long Polling

查看:182
本文介绍了阿贾克斯长轮询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我问一个问题,关于StackOverflow的关于我的一个功能,人们建议我使用Ajax长轮询。我已经在过去几天的研究​​主题和写作过基本的长轮询code,但没有它一直和我不能得到任何我做的工作的。

I recently asked a question on StackOverflow about a function of mine and people recommended that I use Ajax Long Polling. I have spent the past couple of days researching the subject and have tried to write basic long polling code, but none of it has worked and I can not get anything I do to work at all.

下面是我的基本功能:

    <script language='javascript' type='text/javascript'>
    var interval=self.setInterval("checkformessages()",4000)
    function checkformessages() {
    $('#incomingmessages<?php echo $otherchatuser ?>').load('checkfornewmessages.php?username=<?php echo $username; ?>&otherchatuser=<?php echo $otherchatuser; ?>');
    }
    </script>

会有人能告诉我怎么把它变成一个基本的长轮询功能,甚至只是直接说我需要到那里的道路上。任何帮助是非常AP preciated。谢谢!

Would someone be able to tell me how to turn this into a basic long polling function, or even just direct on the path that I need to get there. Any help is very much appreciated. Thanks!

推荐答案

一般(即当不使用长轮询),您的JavaScript code将请求到服务器,然后服务器将信息立即返回。然而,你的服务器可能并不总是要马上说一些重要的事情。在你的榜样(这似乎是一个聊天),你聊天的人可能不会说什么,当你犯了一个请求 checkfornewmessages.php 。因此,当你的JavaScript客户端要求服务器说了些什么,服务器真的没什么,除了与回应什么也没有说。

Usually (i.e. when not using long polling), your JavaScript code will make a request to your server and your server will return with information immediately. However, your server may not always have something important to say immediately. In your example (which seems to be a chat), the person you're chatting with may not have said anything when you make a request to checkfornewmessages.php. Therefore when your JavaScript client asks the server what has been said, the server really has nothing to respond with except "Nothing has been said."

使用长轮询,而不必 checkfornewmessages.php 与立即返回什么也没有说,你根本就没有从 checkfornewmessages返回。 PHP 直到有返回与一些重要的东西。

With long polling instead of having checkfornewmessages.php return immediately with "Nothing has been said," you simply don't return from checkfornewmessages.php until there is something important to return with.

在换句话说,对于长轮询工作,有趣的东西可能是你的 checkfornewmessages.php 页完成在服务器端。你的Javascript code没有做任何事情,除了接触 checkfornewmessages.php 并等待其响应。

In other words, for long polling to work, the interesting stuff is done on the server side probably in your checkfornewmessages.php page. Your javascript code doesn't have to do anything except contact checkfornewmessages.php and wait for it to respond.

这篇关于阿贾克斯长轮询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆