Ajax Long Polling

你。 提交于 2019-11-28 08:47:44

问题


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.

Here is my basic function:

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

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!


回答1:


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.



来源:https://stackoverflow.com/questions/9103490/ajax-long-polling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!