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
220 views
in Technique[技术] by (71.8m points)

javascript - Push changes to a webpage without refreshing

I know that we can do this by polling for changes in regular intervals. And this can be achieved by AJAX (for example using jQuery.load() along with setInterval() ).

But I want to know that are there other methods to do this? Other less costly methods or more efficient methods? What logic an awesome chat client follows? As as soon as you start typing, the other end gets to know that you are typing.

What mechanism do we follow here on stackoverflow to update the upvote count or to show that an edit has been made etc. etc. without the page being refreshed?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

When it comes to keeping the client and server in-sync in (near) real-time, there are 3 things that immediately come to mind:

  • long polling: you already mentioned this one, where you have a timer set on the client which triggers a new AJAX request every 10 seconds or so. This is probably the most "low tech" of the 3 as well as the least efficient; BUT it is also the most compatible (meaning it will work in all browsers, even things like IE6/7)

  • WebSockets: sdespont already mentioned this one in the comments. While WebSockets a more efficient than long-polling (since it just keeps the two way client-server communication open indefinitely), it can be a very heavy-handed solution if all you're trying to do is get regular updates from the server. All versions from Firefox and Chrome support it, and IE added support in IE10

  • Server-sent events: this one seems to be less popular (or just not as well known). It allows the server to send changes to the client (as oppose to the client requesting changes from the server, as is the case with long-polling). This is also just a one-way communication (server --> client) and the connection gets closed after the request is complete (as oppose to WebSockets where 2-way communication stays open). Once again, not all browsers support it, and there is no IE support at all

This is also a good article which explains the difference between the more modern ways of client-server communication. And if you want more info about Server-sent events, this is a good write up


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

...