Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
745 views
in Technique[技术] by (71.8m points)

javascript - How long polling works

I am studying the ajax long polling but I am confused. what is different in traditional ajax calls and long polling

   var lpOnComplete = function(response) {
   alert(response);
   // do more processing
   lpStart();
  };

    var lpStart = function() {
    $.post('/path/to/script', {}, lpOnComplete, 'json');
    };

    $(document).ready(lpStart);

this example is just calling in recursive manner to the server.. what is different than the traditional call in setInterval..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As the name suggest Long Polling means polling something for a long time.

$.post('/path/to/script', {}, lpOnComplete, 'json');

Here is what the actual process starts, You make an ajax call to some script on server, in this case its /path/to/script , You need to make your server script(php for example) smart enough so that it only respond to request's when required data is available, the script should wait for a specified time period(for example 1 minute) and if no data available upto 1 minute then it should return without data.

As soon as server return something, in your callback function you again make an ajax call to the same script and the server script again continues the process.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...