Frage

I want to update a html textarea with the contents of a file on the server. The problem is the file gets updated on the server very often and I want the user to have the latest version all the time (every 100 milliseconds to be precise). Currently what I'm using

<%= IO.read("file_name") %>

and the problem is the file will be read only once (when the user enters the url). Also because of the specifics of my task refreshing the page is not an option.

If it matters I'm using Sinatra on Thin server with Ruby 2.0.

War es hilfreich?

Lösung

I had to learn to write a Sinatra app and that took little time. Here is the solution which works and I am using ERB templates in this code snippet

my_app.rb (Main sinatra application file)

require 'sinatra'
require 'json'
get '/' do
  f = File.open("/home/abcd/my_file.txt","r")
  @contents = f.read()
  f.close()
  erb :home
end
get '/read_file' do 
  f = File.open("/home/abcd/my_file.txt","r")
  contents = f.read()
  f.close()
  if request.xhr?
       halt 200, {:file_contents => contents}.to_json
  else 
     erb :read_file
  end
end

views/home.erb

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="data"><%= @contents %></div>
<script type="text/javascript">
   function update_data() {
  $.ajax({
 url: "/read_file",
 accepts: "application/json",
 dataType: "json",
 success: function(data) {
    $("#data").html(data.file_contents);
 }
  });
   }
   $(document).ready(function() {
#Call update_data every 10 seconds
setInterval(update_data, 10000);
})
</script>

Thank you for asking for code snippet. I learnt a new thing today. Hope this helps.

Andere Tipps

jQuery setInterval would probably work:

setInterval(function(){
    $.get('file_name', function(data){
        $('#div').html(data);
    });
},10000);

Though I'd suggest not writing the function in setInterval() and only reference it. E.G.

function readFile() {
    $.get('file_name', function(data){
        $('#div').html(data);
    });
}
setInterval(readFile, 10000);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top