Rails 3 - Periodic Refresh of DIV

2020-07-30 04:03发布

问题:

I am trying to refresh the contents of a div using AJAX/Unobtrusive JavaScript/JQuery.

This is easy to do if I make a "refresh" link and give it a data-remote attribute.

However, I would like to refresh every 2 seconds using the setInterval function rather than using a link.

This code should demonstrate what I'm trying to do. It does not work when put in application.js because the ERB is not evaluated, but hopefully it will explain my goal.

  setInterval(function(){
    $("#scuttlebutt").html("<%= escape_javascript(render 'scuttlebutt') %>");
  },2000);

What would be a proper way to do this in Rails 3??

(I am working with Rails 3.2.5)

回答1:

Ok, I see what you are trying to do. I have done this before, and I found a simple way of doing it.

You want to still have the button that calls your remote method in a controller that executes some javascript back at the browser to refresh that DIV. I know, I know, you don't want to have it, but here me out. I have one on my page, but I hid it way off to the side so that no one can ever find it, link this:

:id => "refresh_button", :style => "position: absolute; left: -9999px" // Rails ERB notation

Then, I added this to that same file, which I presume is a .html.erb file.

<script type="text/javascript">
  function doSomething() {
    $('#refresh-button').click();
  }

  setInterval('doSomething()',2000);
</script>

This will press the button every 2 seconds, calling your remote function as if some is clicking that button every two seconds. It isn't the cleanest way of doing this, I know, but it works great in a pinch until you can get something more robust working for you. Though you could technically use this.

Hope that helps.



回答2:

I ended up putting code in application.js that would:

  • Check if the div exists
  • Make a timer using setInterval
  • Request a js script from Rails at the current URL which would lead to the evaluating of a js.erb view file. When this file was run it would update my div.

Behold...

assets/javascripts/application.js

$(function() {

  if ($('#scuttlebutt').length) {
    setInterval(function(){
      $.getScript(window.location.pathname, function(data, textStatus, jqxhr) {
        console.log('Load was performed.');
      });
    },2000);
  }

});

views/tickets/show.js.erb

$("#scuttlebutt").html(" <%= escape_javascript(render 'scuttlebutt') %>" );


回答3:

Check out this question.

It states that .js files are not parsed like .erb files. They are passed as-is.