Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

jquery - Ajax Long Polling

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!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...