Skip to content

Instantly share code, notes, and snippets.

@MollsReis
Created November 27, 2012 17:23
Show Gist options
  • Select an option

  • Save MollsReis/4155658 to your computer and use it in GitHub Desktop.

Select an option

Save MollsReis/4155658 to your computer and use it in GitHub Desktop.
example of long polling using sinatra and jquery
require 'json'
require 'haml'
require 'sinatra'
get '/' do
haml :view
end
get '/request' do
content_type :json
num = rand(6) + 1
sleep(num) # simulate work
{ :num => num }.to_json
end
__END__
@@view
!!!
%html
%head
%title longpoll test
%script(type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js")
:javascript
var LongPoll = {
ask: function() {
$.ajax({
url: '/request',
success: function(data) {
$('#test-box').append(data.num);
LongPoll.ask();
},
timeout: 10000
});
}
};
$(document).ready(function() {
LongPoll.ask();
});
%body
%h3 test-box
#test-box
@nafaabout
Copy link
Copy Markdown

This is not long polling, but short polling.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment