Rails 3 - Periodic Refresh of DIV

流过昼夜 提交于 2019-12-04 20:31:32

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.

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') %>" );
Recognizer

Check out this question.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!