简体   繁体   中英

How do I have a page display new information in Sinatra after a server-side process ends?

How do I accomplish displaying new information after a server-side process wraps up?

Here's generally what I have, with some pseudocode in the comments:

require 'sinatra'

get '/' do
  t1 = Thread.new {
    sleep 10
  }
  #if t1 running display 
  #  "Loading..."
  #when t1 ends display
  #  "Successfully accessed this page."
end

In order to use AJAX you have to create an endpoint on your server and use a jQuery or another framework to ease the use of calling the endpoint from javascript. I will paste a short example.

The server could look like this:

require 'sinatra'
set :views, "."

get '/' do
   erb :home
end

get '/ajax_endpoint' do
  t1 = Thread.new {
    sleep 10
  }
  'Done'
  #do the job
end

Put in the views folder (in my case the same as the one the main sinatra app is in) a file with the following content:

<html>
<script src='http://code.jquery.com/jquery-2.0.3.min.js'></script>
<script>
    window.onload = function() {
        $.get('/ajax_endpoint', function(data) {$("#the_div").text("Job done!")})
    }
</script>
 <body>
    <div id='the_div'>
         Loading...
    </div>
 </body>
</html>

In order for the example to work out of the box call the view home.erb.

The main part is calling $.get function. It uses the jQuery frameowrk to make an asynchronous http request at the url you specify as parameter. The second parameter is the callback function for the success. For more informartion about AJAX just use Google, while for jQuery specific use try: http://api.jquery.com/jQuery.ajax/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM