顾名思义,长轮询意味着长时间轮询某事。
$.post('/path/to/script', {}, lpOnComplete, 'json');
这是实际过程的开始,您对服务器上的某个脚本进行 ajax 调用,在这种情况下/path/to/script
,您需要使服务器脚本(php
例如)足够智能,以便它仅在所需数据可用时响应请求,脚本应该等待指定的时间段(例如 1 分钟),如果在 1 分钟内没有可用数据,则它应该返回没有数据。
一旦服务器返回某些内容,在您的回调函数中,您再次对同一脚本进行 ajax 调用,服务器脚本再次继续该过程。
Consider a chat application, In conventional way you are polling the server say every 2 second's and the server return's even if no messages are available.If upto one minute server get's no new messages for you, you end up hitting the server 30 times in last one minute.
Now consider Long Polling way, you set your server script to wait for one minute for the new messages. From the client, you make a single ajax call to your script and say no messages are arriving for next one minute, server will not respond until 1 minute. And you have hit the server just one time in last 1 minute. Can you imagine 30 Hit Vs 1 Hit