如何编写一个基本的长轮询函数?

最近,我在StackOverflow上问了一个关于函数的问题,人们建议我使用Ajax长轮询。在过去的几天里,我一直在研究这个问题,并试图编写基本的长轮询代码,但这些代码都没有起作用。

以下是我的基本功能:

    <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>

有没有人能告诉我如何把它变成一个基本的长轮询函数,或者甚至直接传送到我需要的路径上。任何帮助都是非常感谢的!

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."

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.

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.