简体   繁体   中英

how to reload js.jrs file using ajax

I am building ruby on rails application. I have html partial that contains attribute of an object - @shout.content (text attribute).

In the controller Shout is - @shout = Shout.last

The idea is that @shout changes every time a new shout is created (it changes to be the new shout). I want that every 3 seconds the partial (that contains @shout.content) will "refresh" using ajax.

I thought to put JavaScript function that will be repeated every 3 second:

setInterval( "updateShout()", 3000 ); 

And the updateShout() will run an js.rjs file that will do this:

page.replace_html('content', render(:partial => 'content', :locals => {:content => @shout.content}))

The missing part is the updateShout() function. I don't know how to execute js.rjs file using javascript.

Do you know how can I execute the js.rjs using javascript?

Thanks,

Oded

Given that you (appear) to be using Prototype, you can simplify this greatly. First, instead of your call to setInterval , put this in a <script> tag at the bottom of your page:

new Ajax.PeriodicalUpdater('content', '/path/to/shouts.js', { method: 'get', frequency: 3});

Ensuring that you replace /path/to/shouts.js with the appropriate URL. See periodicalUpdater for more details.

Then, instead of your RJS partial, all you need is the following in your controller:

respond_to do |format|
  format.html
  format.js { render :text => @shout.content }
end

This will render the text of the latest shout in the system and send it back to the browser, leaving PeriodicalUpdater to replace the text in the content div for you.

You are just calling partials,you need to be fire an AJAX query to fetch record,and set ui as per requirement.If you are using jquery then fire AJAX request create js.erb file and called your partial that will generate required HTML,On successful request just update your DOM elements.

$.ajax({
       type: "GET",
       url: "<%= url %>"
     success: function(html){
          $("#content").html(html);
      }
   });

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